pax_global_header00006660000000000000000000000064132544722000014511gustar00rootroot0000000000000052 comment=5440be53845728a9bcc38c76a32a60faa5bf5e38 ripe-atlas-cousteau-1.4.2/000077500000000000000000000000001325447220000154045ustar00rootroot00000000000000ripe-atlas-cousteau-1.4.2/.gitignore000066400000000000000000000004641325447220000174000ustar00rootroot00000000000000*.py[cod] # C extensions *.so # Packages *.egg *.eggs *.egg-info dist build eggs parts bin var sdist develop-eggs .installed.cfg lib lib64 # Unit test / coverage reports .coverage .tox nosetests.xml # Mr Developer .idea/ # virtualenvs python/ # vim swp files *.swp # Sphinx documentation docs/_build/ ripe-atlas-cousteau-1.4.2/.travis.yml000066400000000000000000000004241325447220000175150ustar00rootroot00000000000000language: python sudo: false cache: pip env: - TOXENV=py27 - TOXENV=py34 - TOXENV=pypy-5.3.1 - TOXENV=py27-pyflakes - TOXENV=py27-pep8 - TOXENV=py27-coverage install: - pip install tox - pip install coveralls script: tox after_success: coveralls --verbose ripe-atlas-cousteau-1.4.2/CHANGES.rst000066400000000000000000000142431325447220000172120ustar00rootroot00000000000000Releases History ================ 1.4 (released 2017-04-21) ------------------------- New features: ~~~~~~~~~~~~~ - Expose `bill_to` option for measurement creation - Enable User-Agent for stream connections Changes: ~~~~~~~~ - Update stream channel names to new naming scene in the background Bug Fixes: ~~~~~~~~~~ - Fix bug where stream was not reconnected after a disconnect - Fix unicode cases on the stream spotted by @JonasGroeger 1.3 (released 2016-10-21) ------------------------- Changes: ~~~~~~~~ - Improved streaming support: - Introduce error handling - Channels errors binded by default - Introduced debug mode - Update features set. See all here https://atlas.ripe.net/docs/result-streaming/ - Deprecated short events name and local event name checking. See the event names here https://atlas.ripe.net/docs/result-streaming/ - Introduced support for proxies and additional headers - Timezone aware objects for measurement meta data 1.2 (released 2016-03-02) ------------------------- Changes: ~~~~~~~~ - Backwards incompatible field changes on the Measurement object: - destination_address -> target_ip - destination_asn -> target_asn - destination_name -> target 1.1 (released 2016-02-09) ------------------------- New features: ~~~~~~~~~~~~~ - Start supporting Anchors listing API. - Brand new documentation hosted on readthedocs. Changes: ~~~~~~~~ - Various refactorings to clean up codebase. 1.0.7 (released 2016-01-13) --------------------------- Changes: ~~~~~~~~ - Backwards compatible change of the format we expect for measurement type to handle upcoming change in the API. Bug Fixes: ~~~~~~~~~~ - Fix bug when creating stream for probes connection channel. Updating also wrong documentation. 1.0.6 (released 2015-12-15) --------------------------- Changes: ~~~~~~~~ - Add copyright text everywhere for debian packaging. 1.0.5 (released 2015-12-14) --------------------------- Changes: ~~~~~~~~ - Add tests to the package itself. - Make user-agent changeable by the user. - Various refactorings. 1.0.4 (released 2015-11-06) --------------------------- Changes: ~~~~~~~~ - Handle both string/dictionary as input for probe_ids filter for Result and LatestResult requests. 1.0.2 (released 2015-10-26) --------------------------- Bug Fixes: ~~~~~~~~~~ - Fix bug where key parameter was added to the url even if it was empty. - Fix bug where we didn't try to unjson 4xx responses even if they could contain json structure. 1.0.1 (released 2015-10-23) --------------------------- Changes: ~~~~~~~~ - Now we conform to new API feature that allows for specifying tags when adding probes to existing measurements Bug Fixes: ~~~~~~~~~~ - Fix bug we didn't allow user to specify single tag include/exclude. 1.0 (released 2015-10-21) ------------------------- New features: ~~~~~~~~~~~~~ - Add support for include/exclude tags in changing sources requests. - Add support for latest results API call. - Implement HTTP measurement creation. - Support for python 3 (<=3.4). - Support for pypy/pypy3. - Support for wheels format. Changes: ~~~~~~~~ - Migrate all Atlas requests to use requests library and refactor a lot of code to have a cleaner version. - Create an API v2 translator to address several option name changing. A deprecation warning will be given. Bug Fixes: ~~~~~~~~~~ - Fix bug where python representation of measurements without a stop time was exploding. - Make sure start/stop timestamps in measurement create request are always in UTC. 0.10.1 (released 2015-10-06) ---------------------------- New features: ~~~~~~~~~~~~~ - Implement support for object return in the request generators for probe/measurement. Changes: ~~~~~~~~ - Probe/Measurement python representation takes meta data from v2 API as well. Now everything should point to v2 API. 0.10 (released 2015-10-01) -------------------------- New features: ~~~~~~~~~~~~~ - add object representation of meta data for a probe or a measurement. Changes: ~~~~~~~~ - Abandon v1 RIPE ATLAS API and use only v2. Bug Fixes: ~~~~~~~~~~ - Fix bug that prevented users from specifying all possible source types when they tried to add more probes to existing measurements. - Cover case where a user specified really long list of probes/measurements in the ProbeRequest/MeasurementRequest that was causing 'HTTP ERROR 414: Request-URI Too Long'. Additionally, now if API returns error raise an exception instead of stopping iteration. 0.9.2 (released 2015-09-21) --------------------------- Changes: ~~~~~~~~ - Small refactor of Stream class and manually enforce websockets in SocketIO client 0.9.1 (released 2015-09-03) --------------------------- Bug Fixes: ~~~~~~~~~~ - Fix bug related to binding result atlas stream. 0.9 (released 2015-09-01) ------------------------- New features: ~~~~~~~~~~~~~ - add support for fetching real time results using RIPE Atlas stream server. - this version and on will be available on PYPI. 0.8 (released 2015-08-31) ------------------------- New features: ~~~~~~~~~~~~~ - add support for NTP measurements. 0.7 (released 2015-06-03) ------------------------- New features: ~~~~~~~~~~~~~ - add support for fetching probes/measurements meta data using python generators. 0.6 (released 2014-06-17) ------------------------- New features: ~~~~~~~~~~~~~ - add support for querying results based on start/end time, msm_id and probe id. Changes: ~~~~~~~~ - add http agent according to package version to all requests. 0.5 (released 2014-05-22) ------------------------- Changes: ~~~~~~~~ - change package structure to comply with the new structure of atlas packages - add continuous integration support - add tests - enable travis - enable code health checks - add required files for uploading to github 0.4 (released 2014-03-31) ------------------------- New features: ~~~~~~~~~~~~~ - add support for stopping a measurement. 0.3 (released 2014-02-25) ------------------------- New features: ~~~~~~~~~~~~~ - add simple support for HTTP GET queries. 0.2 (released 2014-02-03) ------------------------- New features: ~~~~~~~~~~~~~ - add support for adding/removing probes API request. Changes: ~~~~~~~~ - use AtlasCreateRequest instead of AtlasRequest for creating a new measurement. 0.1 (released 2014-01-21) ------------------------- - Initial release. ripe-atlas-cousteau-1.4.2/CONTRIBUTING.rst000066400000000000000000000047231325447220000200530ustar00rootroot00000000000000How To Contribute ================= We would love to have contributions from everyone and no contribution is too small. Please submit as many fixes for typos and grammar bloopers as you can! To make participation in this project as pleasant as possible for everyone, we adhere to the `Code of Conduct`_ by the Python Software Foundation. The following steps will help you get started: Fork, then clone the repo: .. code:: bash $ git clone git@github.com:your-username/ripe-atlas-tools.git Make sure the tests pass beforehand: .. code:: bash $ tox or .. code:: bash $ nosetests tests/ Make your changes. Include tests for your change. Make the tests pass: .. code:: bash $ tox or .. code:: bash $ nosetests tests/ Push to your fork and `submit a pull request`_. Here are a few guidelines that will increase the chances of a quick merge of your pull request: - *Always* try to add tests and docs for your code. If a feature is tested and documented, it's easier for us to merge it. - Follow `PEP 8`_. - Write `good commit messages`_. - If you change something that is noteworthy, don't forget to add an entry to the `changes`_. .. note:: - If you think you have a great contribution but aren’t sure whether it adheres -- or even can adhere -- to the rules: **please submit a pull request anyway**! In the best case, we can transform it into something usable, in the worst case the pull request gets politely closed. There’s absolutely nothing to fear. - If you have a great idea but you don't know how or don't have the time to implement it, please consider opening an issue and someone will pick it up as soon as possible. Thank you for considering a contribution to this project! If you have any questions or concerns, feel free to reach out the RIPE Atlas team via the `mailing list`_, `GitHub Issue Queue`_, or `messenger pigeon`_ -- if you must. .. _submit a pull request: https://github.com/RIPE-NCC/ripe-atlas-tools/compare/ .. _PEP 8: https://www.python.org/dev/peps/pep-0008/ .. _good commit messages: http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html .. _Code of Conduct: https://www.python.org/psf/codeofconduct/ .. _changes: https://github.com/RIPE-NCC/ripe-atlas-tools/blob/master/CHANGES.rst .. _mailing list: https://www.ripe.net/mailman/listinfo/ripe-atlas .. _GitHub Issue Queue: https://github.com/RIPE-NCC/ripe-atlas-tools/issues .. _messenger pigeon: https://tools.ietf.org/html/rfc1149 ripe-atlas-cousteau-1.4.2/LICENSE000066400000000000000000001044611325447220000164170ustar00rootroot00000000000000GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 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 General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is 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. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. 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. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. 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 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. Use with the GNU Affero General Public License. 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 Affero 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 special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU 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 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 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 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. {one line to give the program's name and a brief idea of what it does.} Copyright (C) {year} {name of author} This program is free software: you can redistribute it and/or modify it under the terms of the GNU 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: {project} Copyright (C) {year} {fullname} This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". 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 GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ripe-atlas-cousteau-1.4.2/MANIFEST.in000066400000000000000000000002041325447220000171360ustar00rootroot00000000000000include LICENSE include README.rst include MANIFEST.in include CHANGES.rst recursive-include ripe *.py recursive-include tests *.py ripe-atlas-cousteau-1.4.2/README.rst000066400000000000000000000230441325447220000170760ustar00rootroot00000000000000RIPE Atlas Cousteau =================== |Documentation| |Build Status| |Code Health| |PYPI Version| |Python Versions| |Python Implementations| |Python Format| A python wrapper around RIPE ATLAS API. (Until version 0.9.* this wrapper supported v1 API. After version 0.10 and above v2 RIPE ATLAS API is only supported.) Complete documentation can be found on `Read the Docs`_. .. _Read the Docs: http://ripe-atlas-cousteau.readthedocs.org/en/latest/ Installation ------------ You can install by either cloning the repo and run the following inside the repo: .. code:: bash $ python setup.py install or via pip using: .. code:: bash $ pip install ripe.atlas.cousteau Usage ----- Creating a Measurement ~~~~~~~~~~~~~~~~~~~~~~ Creating two new RIPE Atlas UDMs is as easy as: .. code:: python from datetime import datetime from ripe.atlas.cousteau import ( Ping, Traceroute, AtlasSource, AtlasCreateRequest ) ATLAS_API_KEY = "" ping = Ping(af=4, target="www.google.gr", description="testing new wrapper") traceroute = Traceroute( af=4, target="www.ripe.net", description="testing", protocol="ICMP", ) source = AtlasSource(type="area", value="WW", requested=5) atlas_request = AtlasCreateRequest( start_time=datetime.utcnow(), key=ATLAS_API_KEY, measurements=[ping, traceroute], sources=[source], is_oneoff=True ) (is_success, response) = atlas_request.create() Keep in mind that this library is trying to comply with what is stated in the `documentation pages`_. This means that if you try to create a request that is missing a field stated as required, the library won't go ahead and do the HTTP query. On the contrary, it will raise an exception with some info in it. The available measurements types are Ping, Traceroute, Dns, Sslcert, Ntp, Http. .. _documentation pages: https://atlas.ripe.net/docs/api/v2/manual/measurements/types/ Changing Measurement Sources ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Similarly if you want to change (add in the following example) probes for an existing measurement you can do: .. code:: python from ripe.atlas.cousteau import AtlasChangeSource, AtlasChangeRequest ATLAS_MODIFY_API_KEY = "" source = AtlasChangeSource( value="GR", requested=3, type="country", action="add" ) atlas_request = AtlasChangeRequest( key=ATLAS_MODIFY_API_KEY, msm_id=1000001, sources=[source] ) (is_success, response) = atlas_request.create() Same applies if you want to remove probes, you just have to change "action" key to "remove" and specify probes you want to remove. Keep in mind remove action supports only a list of probes and not the rest of the source types. For more info check the appropriate `docs`_. .. _docs: https://atlas.ripe.net/docs/api/v2/reference/#!/participation-requests/Participant_Request_Detail_GET Stopping Measurement ~~~~~~~~~~~~~~~~~~~~ You can stop a measurement with: .. code:: python from ripe.atlas.cousteau import AtlasStopRequest ATLAS_STOP_API_KEY = "" atlas_request = AtlasStopRequest(msm_id=1000001, key=ATLAS_STOP_API_KEY) (is_success, response) = atlas_request.create() In order to be able to successfully create most of the above you need to create an `API key`_. .. _API key: https://atlas.ripe.net/docs/keys/ Tag and untag measurements ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ You can add or remove tags on measurements with: .. code:: python from ripe.atlas.cousteau import MeasurementTagger ATLAS_STOP_API_KEY = "" MSM_ID = 2000001 tagger = MeasurementTagger(key=ATLAS_STOP_API_KEY) (is_success, response) = tagger.add_tag(msm_id=MSM_ID, tag="my-tag") (is_success, response) = tagger.remove_tag(msm_id=MSM_ID, tag="my-tag") Make Any API Get Requests ~~~~~~~~~~~~~~~~~~~~~~~~~ If you know the url path you can make any request easily towards ATLAS API. .. code:: python url_path = "/api/v2/anchors" request = AtlasRequest(**{"url_path": url_path}) result = namedtuple('Result', 'success response') (is_success, response) = request.get() if not is_success: return False return result.response["participant_count"] Fetch Results ~~~~~~~~~~~~~ You can fetch results for any measurements using cousteau. In the following example we are getting all results for measurement ID 2016892 and for probe IDs 1,2,3,4 between 2015-05-19 and 2015-05-20. Times can be python datetime objects, Unix timestamps or string representations of dates. .. code:: python from datetime import datetime from ripe.atlas.cousteau import AtlasResultsRequest kwargs = { "msm_id": 2016892, "start": datetime(2015, 5, 19), "stop": datetime(2015, 5, 20), "probe_ids": [1,2,3,4] } is_success, results = AtlasResultsRequest(**kwargs).create() if is_success: print(results) Fetch real time results ~~~~~~~~~~~~~~~~~~~~~~~ Besides fetching results from main API it is possible to get results though `streaming API`_. .. code:: python from ripe.atlas.cousteau import AtlasStream def on_result_response(*args): """ Function that will be called every time we receive a new result. Args is a tuple, so you should use args[0] to access the real message. """ print args[0] atlas_stream = AtlasStream() atlas_stream.connect() # Measurement results channel = "atlas_result" # Bind function we want to run with every result message received atlas_stream.bind_channel(channel, on_result_response) # Subscribe to new stream for 1001 measurement results stream_parameters = {"msm": 1001} atlas_stream.start_stream(stream_type="result", **stream_parameters) # Probe's connection status results channel = "atlas_probestatus" atlas_stream.bind_channel(channel, on_result_response) stream_parameters = {"enrichProbes": True} atlas_stream.start_stream(stream_type="probestatus", **stream_parameters) # Timeout all subscriptions after 5 secs. Leave seconds empty for no timeout. # Make sure you have this line after you start *all* your streams atlas_stream.timeout(seconds=5) # Shut down everything atlas_stream.disconnect() The available stream parameters for every stream type are described in the `streaming results docs`_ .. _streaming API: https://atlas.ripe.net/docs/result-streaming/ .. _streaming results docs: https://atlas.ripe.net/docs/result-streaming/ Filter Probes/Measurements ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This feature queries API for probes/measurements based on specified filters. Filters should be as specified in `filter_api`_. It hides all the complexity of traversing the API using the next url each time there are more objects. It returns a python generator that you can use to access each object. Fetches all probes from NL with asn\_v4 3333 and with tag NAT .. code:: python from ripe.atlas.cousteau import ProbeRequest filters = {"tags": "NAT", "country_code": "NL", "asn_v4": "3333"} probes = ProbeRequest(**filters) for probe in probes: print(probe["id"]) # Print total count of found probes print(probes.total_count) Fetches all specified measurements. .. code:: python from ripe.atlas.cousteau import MeasurementRequest filters = {"status": 1} measurements = MeasurementRequest(**filters) for msm in measurements: print(msm["msm_id"]) # Print total count of found measurements print(measurements.total_count) .. _filter_api: https://atlas.ripe.net/docs/api/v2/manual/ Represent Probes/Measurements Meta data in python ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This will allow you to have a python object with attributes populated from probes/measurements meta data. Every time you create a new instance it will fetch meta data from API and return an object with selected attributes. .. code:: python from ripe.atlas.cousteau import Probe, Measurement probe = Probe(id=3) print(probe.country_code) print(probe.is_anchor) print(probe.is_public) print(probe.address_v4) print(dir(probe)) # Full list of properties measurement = Measurement(id=1000002) print(measurement.protocol) print(measurement.description) print(measurement.is_oneoff) print(measurement.is_public) print(measurement.target_ip) print(measurement.target_asn) print(measurement.type) print(measurement.interval) print(dir(measurement)) # Full list of properties Colophon ======== But why `Cousteau`_? The RIPE Atlas team decided to name all of its modules after explorers, and this is not an exception :) .. _Cousteau: http://en.wikipedia.org/wiki/Jacques_Cousteau .. |Build Status| image:: https://travis-ci.org/RIPE-NCC/ripe-atlas-cousteau.png?branch=master :target: https://travis-ci.org/RIPE-NCC/ripe-atlas-cousteau .. |Code Health| image:: https://landscape.io/github/RIPE-NCC/ripe-atlas-cousteau/master/landscape.png :target: https://landscape.io/github/RIPE-NCC/ripe-atlas-cousteau/master .. |PYPI Version| image:: https://img.shields.io/pypi/v/ripe.atlas.cousteau.svg .. |Python Versions| image:: https://img.shields.io/pypi/pyversions/ripe.atlas.cousteau.svg .. |Python Implementations| image:: https://img.shields.io/pypi/implementation/ripe.atlas.cousteau.svg .. |Python Format| image:: https://img.shields.io/pypi/format/ripe.atlas.cousteau.svg .. |Documentation| image:: https://readthedocs.org/projects/ripe-atlas-cousteau/badge/?version=latest :target: https://ripe-atlas-cousteau.readthedocs.org/en/latest/?badge=latest ripe-atlas-cousteau-1.4.2/docs/000077500000000000000000000000001325447220000163345ustar00rootroot00000000000000ripe-atlas-cousteau-1.4.2/docs/Makefile000066400000000000000000000170241325447220000200000ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " applehelp to make an Apple Help Book" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" @echo " coverage to run coverage check of the documentation (if enabled)" .PHONY: clean clean: rm -rf $(BUILDDIR)/* .PHONY: html html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." .PHONY: dirhtml dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." .PHONY: singlehtml singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." .PHONY: pickle pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." .PHONY: json json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." .PHONY: htmlhelp htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." .PHONY: qthelp qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/RIPEAtlasCousteau.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/RIPEAtlasCousteau.qhc" .PHONY: applehelp applehelp: $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp @echo @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." @echo "N.B. You won't be able to view it unless you put it in" \ "~/Library/Documentation/Help or install it in your application" \ "bundle." .PHONY: devhelp devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/RIPEAtlasCousteau" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/RIPEAtlasCousteau" @echo "# devhelp" .PHONY: epub epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." .PHONY: latex latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." .PHONY: latexpdf latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." .PHONY: latexpdfja latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." .PHONY: text text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." .PHONY: man man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." .PHONY: texinfo texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." .PHONY: info info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." .PHONY: gettext gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." .PHONY: changes changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." .PHONY: linkcheck linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." .PHONY: doctest doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." .PHONY: coverage coverage: $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage @echo "Testing of coverage in the sources finished, look at the " \ "results in $(BUILDDIR)/coverage/python.txt." .PHONY: xml xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." .PHONY: pseudoxml pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." ripe-atlas-cousteau-1.4.2/docs/changelog.rst000066400000000000000000000000331325447220000210110ustar00rootroot00000000000000.. include:: ../CHANGES.rstripe-atlas-cousteau-1.4.2/docs/conf.py000066400000000000000000000230071325447220000176350ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # RIPE Atlas Cousteau documentation build configuration file, created by # sphinx-quickstart on Wed Jan 13 16:02:54 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os __version__ = None exec(open("../ripe/atlas/cousteau/version.py").read()) # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'RIPE Atlas Cousteau' copyright = u'2016, The RIPE Atlas Team' author = u'astrikos' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = ".".join(__version__.split(".")[:2]) # The full version, including alpha/beta/rc tags. release = ".".join(__version__.split(".")[:3]) # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = 'python' # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. #todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' #html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # Now only 'ja' uses this config value #html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. #html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'RIPEAtlasCousteaudoc' # # Attempt to use the ReadTheDocs theme. If it's not installed, fallback to # the default. # try: import sphinx_rtd_theme html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] except ImportError: pass # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', # Latex figure (float) alignment #'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'RIPEAtlasCousteau.tex', u'RIPE Atlas Cousteau Documentation', u'The RIPE Atlas Team', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'ripeatlascousteau', u'RIPE Atlas Cousteau Documentation', [author], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'RIPE Atlas Cousteau', u'RIPE Atlas Cousteau Documentation', author, 'RIPE Atlas Cousteau', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False ripe-atlas-cousteau-1.4.2/docs/contributing.rst000066400000000000000000000047371325447220000216100ustar00rootroot00000000000000How To Contribute ================= We would love to have contributions from everyone and no contribution is too small. Please submit as many fixes for typos and grammar bloopers as you can! To make participation in this project as pleasant as possible for everyone, we adhere to the `Code of Conduct`_ by the Python Software Foundation. The following steps will help you get started: Fork, then clone the repo: .. code:: bash $ git clone git@github.com:your-username/ripe-atlas-cousteau.git Make sure the tests pass beforehand: .. code:: bash $ tox or .. code:: bash $ nosetests tests/ Make your changes. Include tests for your change. Make the tests pass: .. code:: bash $ tox or .. code:: bash $ nosetests tests/ Push to your fork and `submit a pull request`_. Here are a few guidelines that will increase the chances of a quick merge of your pull request: - *Always* try to add tests and docs for your code. If a feature is tested and documented, it's easier for us to merge it. - Follow `PEP 8`_. - Write `good commit messages`_. - If you change something that is noteworthy, don't forget to add an entry to the `changes`_. .. note:: - If you think you have a great contribution but aren’t sure whether it adheres -- or even can adhere -- to the rules: **please submit a pull request anyway**! In the best case, we can transform it into something usable, in the worst case the pull request gets politely closed. There’s absolutely nothing to fear. - If you have a great idea but you don't know how or don't have the time to implement it, please consider opening an issue and someone will pick it up as soon as possible. Thank you for considering a contribution to this project! If you have any questions or concerns, feel free to reach out the RIPE Atlas team via the `mailing list`_, `GitHub Issue Queue`_, or `messenger pigeon`_ -- if you must. .. _submit a pull request: https://github.com/RIPE-NCC/ripe-atlas-cousteau/compare/ .. _PEP 8: https://www.python.org/dev/peps/pep-0008/ .. _good commit messages: http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html .. _Code of Conduct: https://www.python.org/psf/codeofconduct/ .. _changes: https://github.com/RIPE-NCC/ripe-atlas-cousteau/blob/master/CHANGES.rst .. _mailing list: https://www.ripe.net/mailman/listinfo/ripe-atlas .. _GitHub Issue Queue: https://github.com/RIPE-NCC/ripe-atlas-cousteau/issues .. _messenger pigeon: https://tools.ietf.org/html/rfc1149 ripe-atlas-cousteau-1.4.2/docs/index.html000066400000000000000000000202161325447220000203320ustar00rootroot00000000000000

RIPE Atlas Cousteau

The official python wrapper around RIPE Atlas API. Anyone can use this package to communicate with the RIPE Atlas API in an easier and pythonic way. You will need to have an API key in most of the cases in order your requests to be successful. This wrapper is maintained by RIPE Atlas developers.

Contents:

System Message: ERROR/3 (/Users/astrikos/Development/cousteau/docs/index.rst, line 16)

Unknown directive type "toctree".

.. toctree::
   :maxdepth: 2

ripe-atlas-cousteau-1.4.2/docs/index.rst000066400000000000000000000012401325447220000201720ustar00rootroot00000000000000.. RIPE Atlas Cousteau documentation master file, created by sphinx-quickstart on Wed Jan 13 16:02:54 2016. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. RIPE Atlas Cousteau =================== Welcome to the official python wrapper around RIPE Atlas API. This package can used by anyone to communicate with the RIPE Atlas API using python. You will need to have an API key in most of the cases in order your requests to be successful. This package is maintained by RIPE Atlas developers. Contents: ========= .. toctree:: :maxdepth: 2 installation use contributing changelog ripe-atlas-cousteau-1.4.2/docs/installation.rst000066400000000000000000000030761325447220000215750ustar00rootroot00000000000000.. _requirements-and-installation: Requirements & Installation *************************** .. _installation-requirements: Requirements ============ As you might have guessed, with all of the magic going on under the hood, there are a few dependencies: * `python-dateutil`_ * `socketIO-client>=0.6.5`_ * `requests>=2.7.0`_ Additionally, we recommend that you also install `sphinx`_ if you intend to build the documentation files for offline use. .. _python-dateutil: https://pypi.python.org/pypi/python-dateutil/ .. _socketIO-client>=0.6.5: https://pypi.python.org/pypi/socketIO-client .. _requests>=2.7.0: https://pypi.python.org/pypi/requests .. _sphinx: https://pypi.python.org/pypi/Sphinx/ .. _installation: Installation ============ Installation should be easy, though it may take a while to install all of the aforementioned requirements. Using pip is the recommended method. .. _installation-from-pip: Using pip --------- The quickest and easiest way to install Sagan is to use ``pip``:: $ pip install ripe.atlas.cousteau .. _installation-from-github: From GitHub ----------- If you're feeling a little more daring and want to use whatever is on GitHub, you can have pip install right from there:: $ pip install git+https://github.com/RIPE-NCC/ripe-atlas-cousteau.git .. _installation-from-tarball: From a Tarball -------------- If for some reason you want to just download the source and install it manually, you can always do that too. Simply un-tar the file and run the following in the same directory as ``setup.py``.:: $ python setup.py install ripe-atlas-cousteau-1.4.2/docs/use.rst000066400000000000000000000357741325447220000177020ustar00rootroot00000000000000.. _use-and-examples: Use & Examples ************** This wrapper is using RIPE Atlas v2 API. It covers majority of API calls but not all of them. For some of these calls you will need to have a specific API key tyhat you can get from here. Creating Measurements ===================== .. important:: An `API key`_ is needed with "create a new measurement" permission. You can create multiple measurements with one API request that will share though same start/end time and allocated probes. This means that if you create a ping and a traceroute with one call they will start and finish at the same time and will use same probes. Measurement Types ----------------- The first step is to create the measurement specification object. Currently you can use the following measurement types objects: - Ping - Traceroute - Dns - Sslcert - Ntp - Http You can initialise any of these objects by passing any of arguments stated in the `documentation pages`_. Keep in mind that this library is trying to comply with what is stated in these docs. This means that if you try to create a measurement that is missing a field stated as required in these docs, the library won't go ahead and do the HTTP query. On the contrary, it will raise an exception with some info in it. The required fields for each of the above type are: +-------------+-------------+----------------+-------------+-------------+-------------+ | Ping | Traceroute | Dns | Sslcert | Ntp | Http | +=============+=============+================+=============+=============+=============+ | af | af | af | af | af | af | +-------------+-------------+----------------+-------------+-------------+-------------+ | description | description | description | description | description | description | +-------------+-------------+----------------+-------------+-------------+-------------+ | target | target | query_class | target | target | target | +-------------+-------------+----------------+-------------+-------------+-------------+ | | protocol | query_type | | | | +-------------+-------------+----------------+-------------+-------------+-------------+ | | | query_argument | | | | +-------------+-------------+----------------+-------------+-------------+-------------+ Examples: .. code:: python from ripe.atlas.cousteau import ( Ping, Traceroute ) ping = Ping( af=4, target="www.google.gr", description="Ping Test" ) traceroute = Traceroute( af=4, target="www.ripe.net", description="Traceroute Test", protocol="ICMP", ) Measurement Sources ------------------- The second step is to create the measurements source(s). In order to do that you have to create an AtlasSource object using the arguments type, value, requested, and optionally tags. Type as described in the `documentation pages`_ should be one of the "area", "country", "prefix", "asn", "probes", "msm". Value is the actual value of the type and requested is the number of probes that will be selected from this source. Optionally you can use tags argument, which has to be a dictionary like {"include": [], "exclude": []}. Examples: .. code:: python from ripe.atlas.cousteau import AtlasSource source = AtlasSource( type="area", value="WW", requested=5, tags={"include":["system-ipv4-works"]} ) source1 = AtlasSource( type="country", value="NL", requested=50, tags={"exclude": ["system-anchor"]} ) Create Request -------------- The last step is to make the actual HTTP request. Before you do this you need at least to specify if you measurements will be oneoff and you API key. Additional you can have start and stop time defined. Examples: .. code:: python from datetime import datetime from ripe.atlas.cousteau import ( Ping, Traceroute, AtlasSource, AtlasCreateRequest ) ATLAS_API_KEY = "" ping = Ping(af=4, target="www.google.gr", description="testing new wrapper") traceroute = Traceroute( af=4, target="www.ripe.net", description="testing", protocol="ICMP", ) source = AtlasSource( type="area", value="WW", requested=5, tags={"include":["system-ipv4-works"]} ) source1 = AtlasSource( type="country", value="NL", requested=50, tags={"exclude": ["system-anchor"]} ) atlas_request = AtlasCreateRequest( start_time=datetime.utcnow(), key=ATLAS_API_KEY, measurements=[ping, traceroute], sources=[source, source1], is_oneoff=True ) (is_success, response) = atlas_request.create() Changing Measurement Sources ============================ .. important:: An `API key`_ is needed with "change parameters of a measurement" permission. If you want to add or remove probes from an existing measurement you have to use the AtlasChangeRequest. First step is to create an AtlasChangeSource objects which is similar to AtlasSource object for the creation of measurements. The difference is that here you have to specify an additional action argument. This parameter takes only two values "add" or "remove". In case of "remove" the type of the source can only be "probes". For more info check the appropriate `docs`_. Example: .. code:: python from ripe.atlas.cousteau import AtlasChangeSource, AtlasChangeRequest ATLAS_MODIFY_API_KEY = "" # Add probes source = AtlasChangeSource( value="GR", requested=3, type="country", tags={"include":["system-ipv4-works"], "exclude": ["system-anchor"]}, action="add" ) source1 = AtlasChangeSource( value="4,5,6", requested=3, type="probes", action="add" ) # Remove probes source2 = AtlasChangeSource( value="1,2,3", type="probes", requested=3, action="remove" ) atlas_request = AtlasChangeRequest( key=ATLAS_MODIFY_API_KEY, msm_id=1000001, sources=[source, source1, source2] ) (is_success, response) = atlas_request.create() Stopping Measurement ==================== .. important:: An `API key`_ is needed with "stop a measurement" permission. You can stop a measurement by creating a AtlasStopRequest and specifying measurement ID as shown below: .. code:: python from ripe.atlas.cousteau import AtlasStopRequest ATLAS_STOP_API_KEY = "" atlas_request = AtlasStopRequest(msm_id=1000001, key=ATLAS_STOP_API_KEY) (is_success, response) = atlas_request.create() Results ======= Fetching Results ---------------- .. note:: If measurement is not public you will need an `API key`_ with "download results of a measurement" permission. You can fetch results for any measurements using AtlasResultsRequest. You can filter them by start/end time and probes. Times can be python datetime objects, Unix timestamps or string representations of dates. Example: .. code:: python from datetime import datetime from ripe.atlas.cousteau import AtlasResultsRequest kwargs = { "msm_id": 2016892, "start": datetime(2015, 05, 19), "stop": datetime(2015, 05, 20), "probe_ids": [1,2,3,4] } is_success, results = AtlasResultsRequest(**kwargs).create() if is_success: print(results) Fetching Latest Results ----------------------- .. note:: If measurement is not public you will need an `API key`_ with "download results of a measurement" permission. In case you want to download latest results of a measurement or your measurement is an oneoff measurements is easier and faster to use the API for the latest results. Fetching latest results is done by using AtlasLatestRequest and there is an option for filtering by probes. Example: .. code:: python from ripe.atlas.cousteau import AtlasLatestRequest kwargs = { "msm_id": 2016892, "probe_ids": [1,2,3,4] } is_success, results = AtlasLatestRequest(**kwargs).create() if is_success: print(results) Streaming API ------------- Atlas supports getting results and other events through a stream to get them close to real time. The stream is implemented using websockets and `socket.io`_ protocol. Measurement Results ^^^^^^^^^^^^^^^^^^^ Besides fetching results from main API it is possible to get results though streaming API. You have to use AtlasStream object and bind to "result" channel. You can start the a result stream by specifying at least the measurement ID in the stream parameters. More details on the available parameters of the stream can be found on the `streaming documentation`_. Example: .. code:: python from ripe.atlas.cousteau import AtlasStream def on_result_response(*args): """ Function that will be called every time we receive a new result. Args is a tuple, so you should use args[0] to access the real message. """ print args[0] atlas_stream = AtlasStream() atlas_stream.connect() channel = "result" # Bind function we want to run with every result message received atlas_stream.bind_channel(channel, on_result_response) # Subscribe to new stream for 1001 measurement results stream_parameters = {"msm": 1001} atlas_stream.start_stream(stream_type="result", **stream_parameters) # Timeout all subscriptions after 5 secs. Leave seconds empty for no timeout. # Make sure you have this line after you start *all* your streams atlas_stream.timeout(seconds=5) # Shut down everything atlas_stream.disconnect() Connection Events ^^^^^^^^^^^^^^^^^ Besides results, streaming API supports also probe's connect/disconnect events. Again you have to use AtlasStream object but this time you have to bind to "probe" channel. More info about additional parameters can be found on the `streaming documentation`_. Example: .. code:: python from ripe.atlas.cousteau import AtlasStream def on_result_response(*args): """ Function that will be called every time we receive a new event. Args is a tuple, so you should use args[0] to access the real event. """ print args[0] atlas_stream = AtlasStream() atlas_stream.connect() # Probe's connection status results channel = "probe" atlas_stream.bind_channel(channel, on_result_response) stream_parameters = {"enrichProbes": True} atlas_stream.start_stream(stream_type="probestatus", **stream_parameters) # Timeout all subscriptions after 5 secs. Leave seconds empty for no timeout. # Make sure you have this line after you start *all* your streams atlas_stream.timeout(seconds=5) # Shut down everything atlas_stream.disconnect() .. _socket.io: http://socket.io/ .. _streaming documentation: https://atlas.ripe.net/docs/result-streaming/ Using Sagan Library ------------------- In case you need to do further processing with any of the results you can use our official RIPE Atlas results parsing library called `Sagan`_. An example of how to combine two libraries is the below: .. code:: python from ripe.atlas.cousteau import AtlasLatestRequest from ripe.atlas.sagan import Result kwargs = { "probe_ids": [1,2,3,4] } is_success, results = AtlasLatestRequest(**kwargs).create() if is_success: for result in results: print(Result.get(result)) .. _Sagan: https://github.com/RIPE-NCC/ripe.atlas.sagan Metadata ======== RIPE Atlas API allows you to get metadata about probes and measurements in the system. You can get metadata for a single object or filter based on various criteria. Single Objects -------------- Every time you create a new instance of either Measurement/Probe objects it will fetch meta data from API and return an object with selected attributes. Measurement ^^^^^^^^^^^ Using the Measurement object will allow you to have a python object with attributes populated from specific measurement's meta data. Example: .. code:: python from ripe.atlas.cousteau import Measurement measurement = Measurement(id=1000002) print(measurement.protocol) print(measurement.description) print(measurement.is_oneoff) print(measurement.is_public) print(measurement.target_ip) print(measurement.target_asn) print(measurement.type) print(measurement.interval) print(dir(measurement)) # Full list of properties Probe ^^^^^ Using the Probe object will allow you to have a python object with attributes populated from specific probe's meta data. .. code:: python from ripe.atlas.cousteau import Probe probe = Probe(id=3) print(probe.country_code) print(probe.is_anchor) print(probe.is_public) print(probe.address_v4) print(dir(probe)) # Full list of properties Filtering --------- This feature queries API for probes/measurements based on specified filters. Filters should be according to `filter api documentation`_. Underneath it will follow all next urls until there are no more objects. It returns a python generator that you can use in a for loop to access each object. Probe ^^^^^ The following example will fetch all measurements with Status equals to "Specified". More info on filters for these call are on `probe's filtering documentation`_. .. code:: python from ripe.atlas.cousteau import ProbeRequest filters = {"tags": "NAT", "country_code": "NL", "asn_v4": "3333"} probes = ProbeRequest(**filters) for probe in probes: print(probe["id"]) # Print total count of found probes print(probes.total_count) Measurement ^^^^^^^^^^^ The following example will fetch all probes from NL with asn\_v4 3333 and with tag NAT. More info on filters for these call are on `measurement's filtering documentation`_. .. code:: python from ripe.atlas.cousteau import MeasurementRequest filters = {"status": 1} measurements = MeasurementRequest(**filters) for msm in measurements: print(msm["id"]) # Print total count of found measurements print(measurements.total_count) .. _filter api documentation: https://atlas.ripe.net/docs/rest/ .. _measurement's filtering documentation: https://atlas.ripe.net/docs/rest/#measurement .. _probe's filtering documentation: https://atlas.ripe.net/docs/rest/#probe General GET API Requests ======================== Using the general AtlasRequest object you can do any GET request to the RIPE Atlas API considering you provide the url path. Example: .. code:: python url_path = "/api/v2/anchors" request = AtlasRequest(**{"url_path": url_path}) result = namedtuple('Result', 'success response') (is_success, response) = request.get() if not is_success: return False return result.response["participant_count"] .. _documentation pages: https://atlas.ripe.net/docs/measurement-creation-api/ .. _docs: https://atlas.ripe.net/docs/rest/#participation-request .. _API key: https://atlas.ripe.net/docs/keys/ ripe-atlas-cousteau-1.4.2/ripe/000077500000000000000000000000001325447220000163435ustar00rootroot00000000000000ripe-atlas-cousteau-1.4.2/ripe/__init__.py000066400000000000000000000015031325447220000204530ustar00rootroot00000000000000# Copyright (c) 2016 RIPE NCC # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . try: __import__('pkg_resources').declare_namespace(__name__) except ImportError: from pkgutil import extend_path __path__ = extend_path(__path__, __name__) ripe-atlas-cousteau-1.4.2/ripe/atlas/000077500000000000000000000000001325447220000174475ustar00rootroot00000000000000ripe-atlas-cousteau-1.4.2/ripe/atlas/__init__.py000066400000000000000000000015031325447220000215570ustar00rootroot00000000000000# Copyright (c) 2016 RIPE NCC # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . try: __import__('pkg_resources').declare_namespace(__name__) except ImportError: from pkgutil import extend_path __path__ = extend_path(__path__, __name__) ripe-atlas-cousteau-1.4.2/ripe/atlas/cousteau/000077500000000000000000000000001325447220000212775ustar00rootroot00000000000000ripe-atlas-cousteau-1.4.2/ripe/atlas/cousteau/__init__.py000066400000000000000000000030521325447220000234100ustar00rootroot00000000000000# Copyright (c) 2016 RIPE NCC # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . from .measurement import Ping, Traceroute, Dns, Sslcert, Ntp, Http from .source import AtlasSource, AtlasChangeSource from .request import ( AtlasRequest, AtlasCreateRequest, AtlasChangeRequest, AtlasStopRequest, AtlasLatestRequest, AtlasResultsRequest ) from .stream import AtlasStream from .api_listing import ProbeRequest, MeasurementRequest, AnchorRequest from .api_meta_data import Probe, Measurement from .measurement_tagging import MeasurementTagger __all__ = [ "Ping", "Traceroute", "Dns", "Sslcert", "Ntp", "Http", "AtlasRequest", "AtlasChangeRequest", "AtlasCreateRequest", "AtlasStopRequest", "AtlasLatestRequest", "AtlasResultsRequest", "AtlasSource", "AtlasChangeSource", "AtlasStream", "ProbeRequest", "MeasurementRequest", "AnchorRequest", "Probe", "Measurement", "MeasurementTagger", ] ripe-atlas-cousteau-1.4.2/ripe/atlas/cousteau/api_listing.py000066400000000000000000000154541325447220000241640ustar00rootroot00000000000000# Copyright (c) 2015 RIPE NCC # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import calendar from datetime import datetime try: # Python 3 from urllib.parse import urlparse except ImportError: # Python 2 from urlparse import urlparse from .api_meta_data import Probe, Measurement from .request import AtlasRequest from .exceptions import APIResponseError class RequestGenerator(object): """ Python generator class that yields results for meta APIs like probes/measurements as single objects. It supports any filter APIs support in a dummy way, which means it will take accept whatever it passed and build url_path from this. """ url = "" id_filter = "" URL_LENGTH_LIMIT = 5000 def __init__(self, return_objects=False, user_agent=None, server=None, verify=True, **filters): self._user_agent = user_agent self.server = server self.verify = verify self.api_filters = filters self.split_urls = [] self.total_count_flag = False self.current_batch = [] self._count = [] self.return_objects = return_objects self.atlas_url = self.build_url() def build_url(self): """Build the url path based on the filter options.""" if not self.api_filters: return self.url # Reduce complex objects to simpler strings for k, v in self.api_filters.items(): if isinstance(v, datetime): # datetime > UNIX timestamp self.api_filters[k] = int(calendar.timegm(v.timetuple())) if isinstance(v, (tuple, list)): # tuples & lists > x,y,z self.api_filters[k] = ",".join([str(_) for _ in v]) if ( self.id_filter in self.api_filters and len(str(self.api_filters[self.id_filter])) > self.URL_LENGTH_LIMIT ): self.build_url_chunks() return self.split_urls.pop(0) filters = '&'.join("%s=%s" % (k, v) for (k, v) in self.api_filters.items()) return "%s?%s" % (self.url, filters) def build_url_chunks(self): """ If url is too big because of id filter is huge, break id and construct several urls to call them in order to abstract this complexity from user. """ CHUNK_SIZE = 500 id_filter = str(self.api_filters.pop(self.id_filter)).split(',') chuncks = list(self.chunks(id_filter, CHUNK_SIZE)) filters = '&'.join("%s=%s" % (k, v) for (k, v) in self.api_filters.items()) for chunk in chuncks: if filters: url = "{0}?{1}&{2}={3}".format(self.url, filters, self.id_filter, ','.join(chunk)) else: url = "{0}?{1}={2}".format(self.url, self.id_filter, ','.join(chunk)) self.split_urls.append(url) def chunks(self, l, n): """Yield successive n-sized chunks from l.""" for i in range(0, len(l), n): yield l[i:i + n] def __iter__(self): return self # Python 3 compatibility def __next__(self): return self.next() def next(self): if not self.current_batch: # If first time or current batch was all given if not self.atlas_url: # We don't have any next url any more, exit raise StopIteration() self.next_batch() if not self.current_batch: # Server request gives empty batch, exit raise StopIteration() current_object = self.current_batch.pop(0) if self.return_objects: return self.object_class(meta_data=current_object) else: return current_object def next_batch(self): """ Querying API for the next batch of objects and store next url and batch of objects. """ is_success, results = AtlasRequest( url_path=self.atlas_url, user_agent=self._user_agent, server=self.server, verify=self.verify, ).get() if not is_success: raise APIResponseError(results) self.total_count = results.get("count") self.atlas_url = self.build_next_url(results.get("next")) self.current_batch = results.get("results", []) def build_next_url(self, url): """Builds next url in a format compatible with cousteau. Path + query""" if not url: if self.split_urls: # If we had a long request give the next part self.total_count_flag = False # Reset flag for count return self.split_urls.pop(0) else: return None parsed_url = urlparse(url) return "{0}?{1}".format(parsed_url.path, parsed_url.query) # count attribute to deal with split-up urls and total count def get_total_count(self): """Getter for count attribute""" if not self._count: return 0 else: return sum(self._count) def set_total_count(self, value): """Setter for count attribute. Set should append only one count per splitted url.""" if not self.total_count_flag and value: self._count.append(int(value)) self.total_count_flag = True doc_count = "Defines how many objects returned." total_count = property(get_total_count, set_total_count, doc=doc_count) class ProbeRequest(RequestGenerator): """ Python generator for Probes meta api. e.g. for probe in ProbeRequest(**{"limit":200, "country_code": "GR"}): print(probe["id"]) """ url = "/api/v2/probes/" id_filter = "id__in" object_class = Probe class MeasurementRequest(RequestGenerator): """ Python generator for Measurement meta api. e.g. for measurement in MeasurementRequest(**{"status": 1}): print(measurement["id"]) """ url = "/api/v2/measurements/" id_filter = "id__in" object_class = Measurement class AnchorRequest(RequestGenerator): """ Python generator for Anchor meta api. e.g. for anchor in AnchorRequest(): print(anchor["id"]) """ url = "/api/v2/anchors/" id_filter = "id__in" object_class = None def __init__(self, *args, **kwargs): super(AnchorRequest, self).__init__(*args, **kwargs) self.return_objects = None ripe-atlas-cousteau-1.4.2/ripe/atlas/cousteau/api_meta_data.py000066400000000000000000000150601325447220000244230ustar00rootroot00000000000000# Copyright (c) 2015 RIPE NCC # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . from datetime import datetime from dateutil.tz import tzutc from .request import AtlasRequest from .exceptions import CousteauGenericError, APIResponseError class EntityRepresentation(object): """ A crude representation of entity's meta data as we get it from the API. """ API_META_URL = "" def __init__(self, **kwargs): self.id = kwargs.get("id") self.server = kwargs.get("server") self.verify = kwargs.get("verify", True) self.api_key = kwargs.get("key", "") self.meta_data = kwargs.get("meta_data") self._user_agent = kwargs.get("user_agent") self._fields = kwargs.get("fields") self.get_params = {} if self.meta_data is None and self.id is None: raise CousteauGenericError( "Id or meta_data should be passed in order to create object." ) if self._fields: self.update_get_params() if self.meta_data is None: if not self._fetch_meta_data(): raise APIResponseError(self.meta_data) self._populate_data() def update_get_params(self): """Update HTTP GET params with the given fields that user wants to fetch.""" if isinstance(self._fields, (tuple, list)): # tuples & lists > x,y,z self.get_params["fields"] = ",".join([str(_) for _ in self._fields]) elif isinstance(self._fields, str): self.get_params["fields"] = self._fields def _fetch_meta_data(self): """Makes an API call to fetch meta data for the given probe and stores the raw data.""" is_success, meta_data = AtlasRequest( url_path=self.API_META_URL.format(self.id), key=self.api_key, server=self.server, verify=self.verify, user_agent=self._user_agent ).get(**self.get_params) self.meta_data = meta_data if not is_success: return False return True def _populate_data(self): """ Passing some raw meta data from API response to instance properties """ raise NotImplementedError() class Probe(EntityRepresentation): """ A crude representation of probe's meta data as we get it from the API. """ API_META_URL = "/api/v2/probes/{0}/" def _populate_data(self): """Assing some probe's raw meta data from API response to instance properties""" if self.id is None: self.id = self.meta_data.get("id") self.is_anchor = self.meta_data.get("is_anchor") self.country_code = self.meta_data.get("country_code") self.description = self.meta_data.get("description") self.is_public = self.meta_data.get("is_public") self.asn_v4 = self.meta_data.get("asn_v4") self.asn_v6 = self.meta_data.get("asn_v6") self.address_v4 = self.meta_data.get("address_v4") self.address_v6 = self.meta_data.get("address_v6") self.prefix_v4 = self.meta_data.get("prefix_v4") self.prefix_v6 = self.meta_data.get("prefix_v6") self.geometry = self.meta_data.get("geometry") self.tags = self.meta_data.get("tags") self.status = self.meta_data.get("status", {}).get("name") def __str__(self): return "Probe #{0}".format(self.id) def __repr__(self): return str(self) class Measurement(EntityRepresentation): """ A crude representation of measurement's meta data as we get it from the API. """ API_META_URL = "/api/v2/measurements/{0}/" def _populate_data(self): """Assinging some measurement's raw meta data from API response to instance properties""" if self.id is None: self.id = self.meta_data.get("id") self.stop_time = None self.creation_time = None self.start_time = None self.populate_times() self.protocol = self.meta_data.get("af") self.target_ip = self.meta_data.get("target_ip") self.target_asn = self.meta_data.get("target_asn") self.target = self.meta_data.get("target") self.description = self.meta_data.get("description") self.is_oneoff = self.meta_data.get("is_oneoff") self.is_public = self.meta_data.get("is_public") self.interval = self.meta_data.get("interval") self.resolve_on_probe = self.meta_data.get("resolve_on_probe") self.status_id = self.meta_data.get("status", {}).get("id") self.status = self.meta_data.get("status", {}).get("name") self.type = self.get_type() self.result_url = self.meta_data.get("result") def get_type(self): """ Getting type of measurement keeping backwards compatibility for v2 API output changes. """ mtype = None if "type" not in self.meta_data: return mtype mtype = self.meta_data["type"] if isinstance(mtype, dict): mtype = self.meta_data.get("type", {}).get("name", "").upper() elif isinstance(mtype, str): mtype = mtype return mtype def populate_times(self): """ Populates all different meta data times that comes with measurement if they are present. """ stop_time = self.meta_data.get("stop_time") if stop_time: stop_naive = datetime.utcfromtimestamp(stop_time) self.stop_time = stop_naive.replace(tzinfo=tzutc()) creation_time = self.meta_data.get("creation_time") if creation_time: creation_naive = datetime.utcfromtimestamp(creation_time) self.creation_time = creation_naive.replace(tzinfo=tzutc()) start_time = self.meta_data.get("start_time") if start_time: start_naive = datetime.utcfromtimestamp(start_time) self.start_time = start_naive.replace(tzinfo=tzutc()) def __str__(self): return "Measurement #{0}".format(self.id) def __repr__(self): return str(self) ripe-atlas-cousteau-1.4.2/ripe/atlas/cousteau/exceptions.py000066400000000000000000000015741325447220000240410ustar00rootroot00000000000000# Copyright (c) 2016 RIPE NCC # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . class CousteauGenericError(Exception): """Custom Exception class for cousteau general erorrs.""" pass class APIResponseError(Exception): """Custom Exception class for errors in ATLAS API responses.""" pass ripe-atlas-cousteau-1.4.2/ripe/atlas/cousteau/measurement.py000066400000000000000000000161101325447220000241750ustar00rootroot00000000000000# Copyright (c) 2016 RIPE NCC # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . """ Module containing classes responsible for creating different kind of Atlas measurement objects. """ class AtlasMeasurement(object): """ Parent class for creating an Atlas measurement object containing all needed options for ATLAS API. The different kind of measurements are specified as child classes. These objects can be passed as measurement arguments later on when we call AtlasRequest. Usage: from ripe.atlas.cousteau import Ping ping = Ping(**{ "target": "www.google.gr", "af": 4, "description": "testing new wrapper" }) """ def __init__(self, **kwargs): # set to store all options that are used self.used_options = set() # required options for definitions part self.required_options = ["description", "af"] self.measurement_type = "" def _init(self, **kwargs): """ Initializing required options and set them as attributes as well as options coming from user. """ self._init_required_options(**kwargs) self.add_option(**kwargs) def _store_option(self, option): """ Store option in the used option set. This way we can keep track which options user has select to add to instance. This set is used at the build_api_struct function when we build the desired data structure from user's input. """ self.used_options.add(option) def add_option(self, **options): """ Adds an option and its value to the class as an attribute and stores it to the used options set. """ for option, value in options.items(): setattr(self, option, value) self._store_option(option) def _init_required_options(self, **kwargs): """ Initialize the required option as class members. The value will be either None or the specified value in the kwargs or __init__. The logic here is to make the required options accesible to edit after a class instance has been created. """ for field in self.required_options: setattr(self, field, kwargs.get(field)) self._store_option(field) def clean(self): """ Cleans/checks user entered data making sure required options are at least present. This might save some queries from being sent if they are totally wrong. """ # make sure the correct measurement type is set. if not self.measurement_type: log = "Please define a valid measurement type." raise MalFormattedMeasurement(log) # make sure the required fields are set. for roption in self.required_options: if getattr(self, roption, None) is None: log = "%s Measurement field: <%s> is required" % ( self.__class__.__name__, roption ) raise MalFormattedMeasurement(log) def v2_translator(self, option): """ This is a temporary function that helps move from v1 API to v2 without breaking already running script and keep backwards compatibility. Translates option name from API v1 to renamed one of v2 API. """ new_option = option new_value = getattr(self, option) renaming_pairs = { "dontfrag": "dont_fragment", "maxhops": "max_hops", "firsthop": "first_hop", "use_NSID": "set_nsid_bit", "cd": "set_cd_bit", "do": "set_do_bit", "qbuf": "include_qbuf", "recursion_desired": "set_rd_bit", "noabuf": "include_abuf" } if option in renaming_pairs.keys(): warninglog = ( "DeprecationWarning: {0} option has been deprecated and " "renamed to {1}." ).format(option, renaming_pairs[option]) print(warninglog) new_option = renaming_pairs[option] # noabuf was changed to include_abuf so we need a double-negative if option == "noabuf": new_value = not new_value return new_option, new_value def build_api_struct(self): """ Calls the clean method of the class and returns the info in a structure that Atlas API is accepting. """ self.clean() data = {"type": self.measurement_type} # add all options for option in self.used_options: option_key, option_value = self.v2_translator(option) data.update({option_key: option_value}) return data class Ping(AtlasMeasurement): """Class for creating a ping measurement""" def __init__(self, **kwargs): super(Ping, self).__init__(**kwargs) self.measurement_type = "ping" self.required_options.extend(["target"]) self._init(**kwargs) class Traceroute(AtlasMeasurement): """Class for creating a traceroute measurement""" def __init__(self, **kwargs): super(Traceroute, self).__init__(**kwargs) self.measurement_type = "traceroute" self.required_options.extend(["target", "protocol"]) self._init(**kwargs) class Dns(AtlasMeasurement): """Class for creating a DNS measurement""" def __init__(self, **kwargs): super(Dns, self).__init__(**kwargs) self.measurement_type = "dns" self.required_options.extend( ["query_class", "query_type", "query_argument"] ) self._init(**kwargs) class Sslcert(AtlasMeasurement): """Class for creating an SSL certificate measurement""" def __init__(self, **kwargs): super(Sslcert, self).__init__(**kwargs) self.measurement_type = "sslcert" self.required_options.extend(["target"]) self._init(**kwargs) class Ntp(AtlasMeasurement): """Class for creating an NTP measurement""" def __init__(self, **kwargs): super(Ntp, self).__init__(**kwargs) self.measurement_type = "ntp" self.required_options.extend(["target"]) self._init(**kwargs) class Http(AtlasMeasurement): """Class for creating an HTTP measurement""" def __init__(self, **kwargs): super(Http, self).__init__(**kwargs) self.measurement_type = "http" self.required_options.extend(["target"]) self._init(**kwargs) class MalFormattedMeasurement(Exception): pass __all__ = ["Ping", "Traceroute", "Dns", "Sslcert", "Ntp", "Http"] ripe-atlas-cousteau-1.4.2/ripe/atlas/cousteau/measurement_tagging.py000066400000000000000000000031461325447220000257020ustar00rootroot00000000000000from .request import AtlasRequest class MeasurementTagRemoveRequest(AtlasRequest): url_path_tmpl = "/api/v2/measurements/{msm_id}/tags/{tag}/" def __init__(self, **kwargs): super(MeasurementTagRemoveRequest, self).__init__(**kwargs) self.msm_id = kwargs["msm_id"] self.tag = kwargs["tag"] self.url_path = self.url_path_tmpl.format( msm_id=self.msm_id, tag=self.tag ) def create(self): return self.http_method("DELETE") class MeasurementTagAddRequest(AtlasRequest): url_path_tmpl = "/api/v2/measurements/{msm_id}/tags/" def __init__(self, **kwargs): super(MeasurementTagAddRequest, self).__init__(**kwargs) self.tag = kwargs.pop("tag") self.msm_id = kwargs.pop("msm_id") self.url_path = self.url_path_tmpl.format(msm_id=self.msm_id) def _construct_post_data(self): self.post_data = { "tag": self.tag } def create(self): return self.post() class MeasurementTagger(object): def __init__(self, **kwargs): self.defaults = kwargs def add_tag(self, msm_id, tag, **kwargs): req_kwargs = self.defaults.copy() req_kwargs.update(kwargs) request = MeasurementTagAddRequest( msm_id=msm_id, tag=tag, **req_kwargs ) return request.create() def remove_tag(self, msm_id, tag, **kwargs): req_kwargs = self.defaults.copy() req_kwargs.update(kwargs) request = MeasurementTagRemoveRequest( msm_id=msm_id, tag=tag, **req_kwargs ) return request.create() ripe-atlas-cousteau-1.4.2/ripe/atlas/cousteau/request.py000066400000000000000000000251611325447220000233460ustar00rootroot00000000000000# Copyright (c) 2016 RIPE NCC # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . """ Module containing the main class that create the post data and makes the HTTP request according to the ATLAS API. """ import calendar import requests from dateutil import parser from datetime import datetime from .version import __version__ class AtlasRequest(object): """ Base class for doing Atlas requests. Contains functions that can be used by most Atlas requests. """ http_methods = { "GET": requests.get, "POST": requests.post, "DELETE": requests.delete } def __init__(self, **kwargs): self.url = "" self.key = kwargs.get("key") self.url_path = kwargs.get("url_path", "") self.server = kwargs.get("server") or "atlas.ripe.net" self.verify = kwargs.get("verify", True) self.proxies = kwargs.get("proxies", {}) self.headers = kwargs.get("headers", None) default_user_agent = "RIPE ATLAS Cousteau v{0}".format(__version__) self.http_agent = kwargs.get("user_agent") or default_user_agent self.http_method_args = { "params": {"key": self.key}, "headers": self.get_headers(), "verify": self.verify, "proxies": self.proxies } self.post_data = {} def get_headers(self): """Return header for the HTTP request.""" headers = { "User-Agent": self.http_agent, "Content-Type": "application/json", "Accept": "application/json" } if self.headers: headers.update(self.headers) return headers def http_method(self, method): """ Execute the given HTTP method and returns if it's success or not and the response as a string if not success and as python object after unjson if it's success. """ self.build_url() try: response = self.get_http_method(method) is_success = response.ok try: response_message = response.json() except ValueError: response_message = response.text except requests.exceptions.RequestException as exc: is_success = False response_message = exc.args return is_success, response_message def get_http_method(self, method): """Gets the http method that will be called from the requests library""" return self.http_methods[method](self.url, **self.http_method_args) def build_url(self): """ Builds the request's url combining server and url_path classes attributes. """ self.url = "https://{0}{1}".format(self.server, self.url_path) def get(self, **url_params): """ Makes the HTTP GET to the url. """ if url_params: self.http_method_args["params"].update(url_params) return self.http_method("GET") def post(self): """ Makes the HTTP POST to the url sending post_data. """ self._construct_post_data() post_args = {"json": self.post_data} self.http_method_args.update(post_args) return self.http_method("POST") def _construct_post_data(self): raise NotImplementedError def clean_time(self, time): """ Transform time field to datetime object if there is any. """ if isinstance(time, int): time = datetime.utcfromtimestamp(time) elif isinstance(time, str): time = parser.parse(time) return time class AtlasCreateRequest(AtlasRequest): """ Class responsible for creating a request for creating a new Atlas measurement. Takes as arguments Atlas API key, a list of Atlas measurement objects and a list of Atlas sources. Optionally the start and end time and whether the measurement is a oneoff can be specified. Usage: from ripe.atlas import AtlasCreateRequest ar = AtlasCreateRequest(**{ "start_time": start, "stop_time": stop, "key": "path_to_key", "measurements":[measurement1, ...], "sources": [source1, ...], "is_oneoff": True/False }) ar.create() """ def __init__(self, **kwargs): super(AtlasCreateRequest, self).__init__(**kwargs) self.url_path = '/api/v2/measurements/' self.measurements = kwargs["measurements"] self.sources = kwargs["sources"] self.start_time = self.clean_time(kwargs.get("start_time")) self.stop_time = self.clean_time(kwargs.get("stop_time")) self.bill_to = kwargs.get("bill_to") if kwargs.get("is_oneoff"): self.is_oneoff = kwargs["is_oneoff"] else: self.is_oneoff = False def _construct_post_data(self): """ Constructs the data structure that is required from the atlas API based on measurements, sources and times user has specified. """ definitions = [msm.build_api_struct() for msm in self.measurements] probes = [source.build_api_struct() for source in self.sources] self.post_data = { "definitions": definitions, "probes": probes, "is_oneoff": self.is_oneoff } if self.is_oneoff: self.post_data.update({"is_oneoff": self.is_oneoff}) if self.start_time: self.post_data.update( {"start_time": int(calendar.timegm(self.start_time.timetuple()))} ) if self.stop_time: self.post_data.update( {"stop_time": int(calendar.timegm(self.stop_time.timetuple()))} ) if self.bill_to: self.post_data.update({"bill_to": self.bill_to}) def create(self): """Sends the POST request""" return self.post() class AtlasChangeRequest(AtlasRequest): """Atlas request for changing probes for a running measurement. post_data = [{ "action": "add|remove", "requested": probe_number, # when action=remove only probes is supported "type": "area|country|asn|prefix|msm|probes", "value": probe_values }] """ def __init__(self, **kwargs): super(AtlasChangeRequest, self).__init__(**kwargs) self.url_path = '/api/v2/measurements/{0}/participation-requests/' self.msm_id = kwargs["msm_id"] self.sources = kwargs["sources"] self.url_path = self.url_path.format(self.msm_id) def _construct_post_data(self): """ Constructs the data structure that is required from the atlas API based on measurement id, and the sources. """ self.post_data = [source.build_api_struct() for source in self.sources] def create(self): """Sends the POST request""" return self.post() class AtlasStopRequest(AtlasRequest): """Atlas request for stopping a measurement.""" def __init__(self, **kwargs): super(AtlasStopRequest, self).__init__(**kwargs) self.url_path = '/api/v2/measurements/' self.msm_id = kwargs["msm_id"] self.url_path = "{0}{1}".format(self.url_path, self.msm_id) def delete(self): """ Makes the HTTP DELETE to the url. """ return self.http_method("DELETE") def create(self): """Sends the DELETE request""" return self.delete() class AtlasLatestRequest(AtlasRequest): def __init__(self, msm_id=None, probe_ids=(), **kwargs): super(AtlasLatestRequest, self).__init__(**kwargs) self.url_path = "/api/v2/measurements/{0}/latest" self.msm_id = msm_id self.probe_ids = None self.url_path = self.url_path.format(self.msm_id) if probe_ids: self.add_probe_parameters(probe_ids) def add_probe_parameters(self, probe_ids): """ Creates string format if needed and add probe ids to HTTP query parameters. """ if isinstance(probe_ids, (tuple, list)): # tuples & lists > x,y,z self.probe_ids = ",".join([str(_) for _ in probe_ids]) else: self.probe_ids = probe_ids additional_params = { "probe_ids": self.probe_ids } self.http_method_args["params"].update(additional_params) def create(self): """Sends the GET request.""" return self.get() class AtlasResultsRequest(AtlasRequest): """Atlas request for fetching results of a measurement.""" def __init__(self, **kwargs): super(AtlasResultsRequest, self).__init__(**kwargs) self.url_path = '/api/v2/measurements/{0}/results' self.msm_id = kwargs["msm_id"] self.start = self.clean_time(kwargs.get("start")) self.stop = self.clean_time(kwargs.get("stop")) self.probe_ids = self.clean_probes(kwargs.get("probe_ids")) self.url_path = self.url_path.format(self.msm_id) self.update_http_method_params() def clean_probes(self, probe_ids): """ Checks format of probe ids and transform it to something API understands. """ if isinstance(probe_ids, (tuple, list)): # tuples & lists > x,y,z probe_ids = ",".join([str(_) for _ in probe_ids]) return probe_ids def update_http_method_params(self): """ Update HTTP url parameters based on msm_id and query filters if there are any. """ url_params = {} if self.start: url_params.update( {"start": int(calendar.timegm(self.start.timetuple()))} ) if self.stop: url_params.update( {"stop": int(calendar.timegm(self.stop.timetuple()))} ) if self.probe_ids: url_params.update({"probe_ids": self.probe_ids}) self.http_method_args["params"].update(url_params) def create(self): """Sends the GET request.""" return self.get() __all__ = [ "AtlasStopRequest", "AtlasCreateRequest", "AtlasChangeRequest", "AtlasRequest", "AtlasResultsRequest" ] ripe-atlas-cousteau-1.4.2/ripe/atlas/cousteau/source.py000066400000000000000000000172351325447220000231610ustar00rootroot00000000000000# Copyright (c) 2016 RIPE NCC # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . """ Module containing class responsible for creating different Atlas source objects """ class AtlasSource(object): """ Class responsible for creating an Atlas source object that holds information about the number of probes, the type of the source and the value of the source. This object can be passed as source argument later on when we call AtlasRequest. Usage: from ripe.atlas.cousteau import AtlasSource as = AtlasSource(**{"type": "area", "value": "WW", "requested": 5}) """ # available types types_available = ["area", "country", "prefix", "asn", "probes", "msm"] def __init__(self, **kwargs): if "requested" in kwargs: self.requested = kwargs["requested"] else: self._requested = None if "value" in kwargs: self.value = kwargs["value"] else: self._value = None if "type" in kwargs: self.type = kwargs["type"] else: self._type = None if "tags" in kwargs: self.tags = kwargs["tags"] else: self._tags = None # requested attribute def get_requested(self): """Getter for requested attribute""" return self._requested def set_requested(self, value): """Setter for requested attribute""" self._requested = value doc_req = "Defines how many probes will be requested." requested = property(get_requested, set_requested, doc=doc_req) # value attribute def get_value(self): """Getter for value attribute""" return self._value def set_value(self, value): """Setter for value attribute""" self._value = value doc_value = "Defines the value of the type of probe's source." value = property(get_value, set_value, doc=doc_value) # type attribute def get_type(self): """Getter for type attribute""" return self._type def set_type(self, value): """Setter for type attribute""" if value not in self.types_available: log = "Sources field 'type' should be in one of %s" % ( self.types_available ) raise MalFormattedSource(log) self._type = value doc_type = "Defines the type of probe's source." type = property(get_type, set_type, doc=doc_type) # tags attribute def get_tags(self): """Getter for tags attribute""" return self._tags def set_tags(self, value): """Setter for tags attribute""" log = ( 'Sources fields "tags" should be a dict in the format ' '{"include": [ "tag1", "tag2", "tagN" ],' '"exclude": [ "tag1", "tag2", "tagN" ] }' ) if not isinstance(value, dict): raise MalFormattedSource(log) if not set(value.keys()).issubset(set(["include", "exclude"])): raise MalFormattedSource(log) for tag_list in value.values(): if not isinstance(tag_list, list): raise MalFormattedSource(log) if [tag for tag in tag_list if not isinstance(tag, str)]: raise MalFormattedSource(log) self._tags = value doc_tags = "Defines optional tags to filter probes." tags = property(get_tags, set_tags, doc=doc_tags) def clean(self): """ Cleans/checks user has entered all required attributes. This might save some queries from being sent to server if they are totally wrong. """ if not all([self._requested, self._value, self._type]): raise MalFormattedSource( " fields are required." ) def build_api_struct(self): """ Calls the clean method of the class and returns the info in a structure that Atlas API is accepting. """ self.clean() r = { "type": self._type, "requested": self._requested, "value": self._value } if self._tags: r["tags"] = self._tags return r class AtlasChangeSource(AtlasSource): """ Class responsible for creating an Atlas source object for changing participants probes for a measurement. Usage: from ripe.atlas.cousteau import AtlasChangeSource as = AtlasChangeSource(**{"type":"area", "value": "WW", "requested": 5}) """ def __init__(self, **kwargs): if "action" in kwargs: self.action = kwargs["action"] else: self._action = None super(AtlasChangeSource, self).__init__(**kwargs) # type attribute def get_type(self): """Getter for type attribute""" return self._type def set_type(self, value): """Setter for type attribute""" if self.action == "remove" and value != "probes": log = "Sources field 'type' when action is remove should always be 'probes'." raise MalFormattedSource(log) self._type = value doc_type = "Defines the type of probe's source." type = property(get_type, set_type, doc=doc_type) # tags attribute def get_tags(self): """Getter for tags attribute""" return self._tags def set_tags(self, value): """Setter for tags attribute""" if self.action == "remove": log = ( "Tag-based filtering can only be used when adding " "participant probes for a measurement." ) raise MalFormattedSource(log) super(AtlasChangeSource, self).set_tags(value) doc_tags = "Defines optional tags to filter probes." tags = property(get_tags, set_tags, doc=doc_tags) # action attribute def get_action(self): """Getter for action attribute""" return self._action def set_action(self, value): """Setter for action attribute""" if value not in ("remove", "add"): log = "Sources field 'action' should be 'remove' or 'add'." raise MalFormattedSource(log) self._action = value doc_action = "Defines the action (remove/add if the change source)." action = property(get_action, set_action, doc=doc_action) def clean(self): """ Cleans/checks user has entered all required attributes. This might save some queries from being sent to server if they are totally wrong. """ if not all([self._type, self._requested, self._value, self._action]): raise MalFormattedSource( " fields are required." ) def build_api_struct(self): """ Calls parent's method and just adds the addtional field 'action', that is required to form the structure that Atlas API is accepting. """ data = super(AtlasChangeSource, self).build_api_struct() data.update({"action": self._action}) return data class MalFormattedSource(Exception): """Custom Exception class for malformed sources""" pass __all__ = ["AtlasSource", "AtlasChangeSource"] ripe-atlas-cousteau-1.4.2/ripe/atlas/cousteau/stream.py000066400000000000000000000133301325447220000231440ustar00rootroot00000000000000# Copyright (c) 2016 RIPE NCC # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import logging import hashlib from functools import partial from socketIO_client import SocketIO, BaseNamespace from .version import __version__ try: from logging import NullHandler except ImportError: # Python 2.6 from logging import Handler class NullHandler(Handler): def emit(self, record): pass LOG = logging.getLogger('atlas-stream') LOG.addHandler(NullHandler()) class AtlasNamespace(BaseNamespace): SUBSCRIPTIONS = {} def on_connect(self, *args): LOG.debug("Connected to RIPE Atlas Stream") def on_disconnect(self, *args): LOG.debug("Disconnected from RIPE Atlas Stream") def on_reconnect(self, *args): LOG.debug("Reconnected to RIPE Atlas Stream") LOG.debug("Trying to attach to existed subscriptions") for subscription in self.SUBSCRIPTIONS.values(): LOG.debug("Subscribing to {}".format(subscription)) self.emit("atlas_subscribe", subscription) def on_atlas_result(self, *args): LOG.info(args[0]) def on_atlas_subscribed(self, *args): LOG.debug("Subscribed to subscription: {}".format(args[0])) hash_object = hashlib.sha1(str(args[0]).encode('utf-8')) hex_dig = hash_object.hexdigest() self.SUBSCRIPTIONS[hex_dig] = args[0] def on_atlas_error(self, *args): LOG.error("Got an error from stream server: {}".format(args[0])) class AtlasStream(object): EVENT_NAME_RESULTS = "atlas_result" EVENT_NAME_SUBSCRIBE = "atlas_subscribe" EVENT_NAME_ERROR = "atlas_error" # Remove the following list when deprecation time expires CHANNELS = { "result": "atlas_result", "probe": "atlas_probestatus", "error": "atlas_error", } # ------------------------------------------------------- def __init__(self, debug=False, server=False, proxies=None, headers=None): """Initialize stream""" self.iosocket_server = "atlas-stream.ripe.net" self.iosocket_resource = "/stream/socket.io" self.socketIO = None self.debug = debug self.error_callback = None self.proxies = proxies or {} self.headers = headers or {} if not self.headers or not self.headers.get("User-Agent", None): user_agent = "RIPE ATLAS Cousteau v{0}".format(__version__) self.headers["User-Agent"] = user_agent if self.debug and server: self.iosocket_server = server def handle_error(self, error): if self.error_callback is not None: self.error_callback(error) else: print(error) def connect(self): """Initiate the channel we want to start streams from.""" self.socketIO = SocketIO( host=self.iosocket_server, port=80, resource=self.iosocket_resource, proxies=self.proxies, headers=self.headers, transports=["websocket"], Namespace=AtlasNamespace, ) self.socketIO.on(self.EVENT_NAME_ERROR, self.handle_error) def disconnect(self): """Exits the channel k shuts down connection.""" self.socketIO.disconnect() self.socketIO.__exit__([]) def unpack_results(self, callback, data): if isinstance(data, list): for result in data: callback(result) else: callback(data) def bind_channel(self, channel, callback): """Bind given channel with the given callback""" # Remove the following list when deprecation time expires if channel in self.CHANNELS: warning = ( "The event name '{}' will soon be deprecated. Use " "the real event name '{}' instead." ).format(channel, self.CHANNELS[channel]) self.handle_error(warning) channel = self.CHANNELS[channel] # ------------------------------------------------------- if channel == self.EVENT_NAME_ERROR: self.error_callback = callback elif channel == self.EVENT_NAME_RESULTS: self.socketIO.on(channel, partial(self.unpack_results, callback)) else: self.socketIO.on(channel, callback) def start_stream(self, stream_type, **stream_parameters): """Starts new stream for given type with given parameters""" if stream_type: self.subscribe(stream_type, **stream_parameters) else: self.handle_error("You need to set a stream type") def subscribe(self, stream_type, **parameters): """Subscribe to stream with give parameters.""" parameters["stream_type"] = stream_type if (stream_type == "result") and ("buffering" not in parameters): parameters["buffering"] = True self.socketIO.emit(self.EVENT_NAME_SUBSCRIBE, parameters) def timeout(self, seconds=None): """ Times out all streams after n seconds or wait forever if seconds is None """ if seconds is None: self.socketIO.wait() else: self.socketIO.wait(seconds=seconds) ripe-atlas-cousteau-1.4.2/ripe/atlas/cousteau/version.py000066400000000000000000000012611325447220000233360ustar00rootroot00000000000000# Copyright (c) 2016 RIPE NCC # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . __version__ = "1.4.2" ripe-atlas-cousteau-1.4.2/setup.cfg000066400000000000000000000000261325447220000172230ustar00rootroot00000000000000[wheel] universal = 1 ripe-atlas-cousteau-1.4.2/setup.py000066400000000000000000000035011325447220000171150ustar00rootroot00000000000000#!/usr/bin/env python from os.path import abspath, dirname, join from setuptools import setup # import manually __version__ variable __version__ = None exec(open('ripe/atlas/cousteau/version.py').read()) install_requires = [ "python-dateutil", "socketIO-client>=0.6.5", "requests>=2.7.0", "websocket-client<0.99" ] tests_require = [ "funcsigs", "setuptools", "nose", "coverage", "mock", "jsonschema" ] # Get proper long description for package current_dir = dirname(abspath(__file__)) description = open(join(current_dir, "README.rst")).read() changes = open(join(current_dir, "CHANGES.rst")).read() long_description = '\n\n'.join([description, changes]) setup( name="ripe.atlas.cousteau", version=__version__, packages=["ripe", "ripe.atlas", "ripe.atlas.cousteau"], namespace_packages=["ripe", "ripe.atlas"], include_package_data=True, license="GPLv3", url="https://github.com/RIPE-NCC/ripe-atlas-cousteau", description="Python wrapper for RIPE Atlas API", long_description=long_description, author="The RIPE Atlas Team", author_email="atlas@ripe.net", maintainer="The RIPE Atlas Team", maintainer_email="atlas@ripe.net", install_requires=install_requires, tests_require=tests_require, test_suite="nose.collector", keywords=['RIPE', 'RIPE NCC', 'RIPE Atlas'], classifiers=[ "Operating System :: POSIX", "Operating System :: Unix", "Programming Language :: Python", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Internet :: WWW/HTTP", "Topic :: Software Development :: Libraries :: Python Modules" ] ) ripe-atlas-cousteau-1.4.2/tests/000077500000000000000000000000001325447220000165465ustar00rootroot00000000000000ripe-atlas-cousteau-1.4.2/tests/__init__.py000066400000000000000000000062741325447220000206700ustar00rootroot00000000000000# Copyright (c) 2015 RIPE NCC # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . definitions_schema = { "type": "object", "required": ["type", "af", "description"], "properties": { "type": { "type": "string", "enum": ["ping", "traceroute", "dns", "sslcert"] }, "af": { "type": "integer", "enum": [4, 6] }, "description": { "type": "string", }, "target": { "type": "string", }, "is_oneoff": { "type": "boolean", }, "interval": { "type": "integer", }, } } probes_create_schema = { "type": "object", "required": ["requested", "type", "value"], "properties": { "requested": { "type": "integer", }, "type": { "type": "string", "enum": [ "area", "country", "prefix", "asn", "probes", "msm" ] }, "value": { "type": "string", }, "tags": { "type": "object", "required": ["include", "exclude"], "properties": { "include": { "type": "array", "items": {"type": "string"} }, "exclude": { "type": "array", "items": {"type": "string"} } } } } } post_data_create_schema = { "type": "object", "required": ["definitions", "probes"], "properties": { "definitions": { "type": "array", "items": definitions_schema }, "start_time": {"type": "integer"}, "end_time": {"type": "integer"}, "is_oneoff": {"type": "boolean"}, "probes": { "type": "array", "items": probes_create_schema } } } probes_change_schema = { "type": "object", "required": ["requested", "type", "value", "action"], "properties": { "requested": { "type": "integer", }, "type": { "type": "string", "enum": ["area", "country", "prefix", "asn", "probes", "msm"] }, "value": { "type": "string", }, "action": { "type": "string", "enum": ["add", "remove"] }, } } post_data_change_schema = { "type": "array", "items": probes_change_schema } __all__ = [ "definitions_schema", "probes_create_schema", "probes_change_schema", "post_data_create_schema", "post_data_change_schema" ] ripe-atlas-cousteau-1.4.2/tests/test_api_listing.py000066400000000000000000000502421325447220000224640ustar00rootroot00000000000000# Copyright (c) 2015 RIPE NCC # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # Python 3.4+ comes with mock in unittest try: from unittest import mock except ImportError: import mock from unittest import TestCase from ripe.atlas.cousteau.api_listing import RequestGenerator from ripe.atlas.cousteau import ( ProbeRequest, AnchorRequest, MeasurementRequest ) from ripe.atlas.cousteau.exceptions import APIResponseError class TestRequestGenerator(TestCase): def test_build_url(self): def decostruct_url_params(url_params): """ Pure man's way of splitting args to avoid unpredicted output from python hashed dict keys """ params = url_params.split("&") params[0] = params[0][1:] return set(params) kwargs = {"limit": "100", "asn": "3333"} r = RequestGenerator(**kwargs) self.assertEqual( decostruct_url_params(r.build_url()), set(["limit=100", "asn=3333"]) ) kwargs = {"limit": "100", "asn": "3333", "tags": "NAT,system-ipv4-works"} r = RequestGenerator(**kwargs) self.assertEqual( decostruct_url_params(r.build_url()), set(["limit=100", "tags=NAT,system-ipv4-works", "asn=3333"]) ) kwargs = {"asn": "3333"} r = RequestGenerator(**kwargs) self.assertEqual( r.build_url(), "?asn=3333" ) kwargs = {"limit": "10"} r = RequestGenerator(**kwargs) self.assertEqual( r.build_url(), "?limit=10" ) kwargs = {} r = RequestGenerator(**kwargs) self.assertEqual( r.build_url(), "" ) def test_empty_response_with_no_success(self): arequest = mock.patch('ripe.atlas.cousteau.request.AtlasRequest.get').start() arequest.return_value = False, {} kwargs = {"id__in": range(1, 10)} r = ProbeRequest(**kwargs) self.assertRaises(APIResponseError, lambda: list(r)) def test_long_id_filter(self): kwargs = {"id__in": ",".join(map(str, range(1, 2000)))} r = ProbeRequest(**kwargs) expected_list = ['/api/v2/probes/?id__in=501,502,503,504,505,506,507,508,509,510,511,512,513,514,515,516,517,518,519,520,521,522,523,524,525,526,527,528,529,530,531,532,533,534,535,536,537,538,539,540,541,542,543,544,545,546,547,548,549,550,551,552,553,554,555,556,557,558,559,560,561,562,563,564,565,566,567,568,569,570,571,572,573,574,575,576,577,578,579,580,581,582,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,611,612,613,614,615,616,617,618,619,620,621,622,623,624,625,626,627,628,629,630,631,632,633,634,635,636,637,638,639,640,641,642,643,644,645,646,647,648,649,650,651,652,653,654,655,656,657,658,659,660,661,662,663,664,665,666,667,668,669,670,671,672,673,674,675,676,677,678,679,680,681,682,683,684,685,686,687,688,689,690,691,692,693,694,695,696,697,698,699,700,701,702,703,704,705,706,707,708,709,710,711,712,713,714,715,716,717,718,719,720,721,722,723,724,725,726,727,728,729,730,731,732,733,734,735,736,737,738,739,740,741,742,743,744,745,746,747,748,749,750,751,752,753,754,755,756,757,758,759,760,761,762,763,764,765,766,767,768,769,770,771,772,773,774,775,776,777,778,779,780,781,782,783,784,785,786,787,788,789,790,791,792,793,794,795,796,797,798,799,800,801,802,803,804,805,806,807,808,809,810,811,812,813,814,815,816,817,818,819,820,821,822,823,824,825,826,827,828,829,830,831,832,833,834,835,836,837,838,839,840,841,842,843,844,845,846,847,848,849,850,851,852,853,854,855,856,857,858,859,860,861,862,863,864,865,866,867,868,869,870,871,872,873,874,875,876,877,878,879,880,881,882,883,884,885,886,887,888,889,890,891,892,893,894,895,896,897,898,899,900,901,902,903,904,905,906,907,908,909,910,911,912,913,914,915,916,917,918,919,920,921,922,923,924,925,926,927,928,929,930,931,932,933,934,935,936,937,938,939,940,941,942,943,944,945,946,947,948,949,950,951,952,953,954,955,956,957,958,959,960,961,962,963,964,965,966,967,968,969,970,971,972,973,974,975,976,977,978,979,980,981,982,983,984,985,986,987,988,989,990,991,992,993,994,995,996,997,998,999,1000', '/api/v2/probes/?id__in=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1011,1012,1013,1014,1015,1016,1017,1018,1019,1020,1021,1022,1023,1024,1025,1026,1027,1028,1029,1030,1031,1032,1033,1034,1035,1036,1037,1038,1039,1040,1041,1042,1043,1044,1045,1046,1047,1048,1049,1050,1051,1052,1053,1054,1055,1056,1057,1058,1059,1060,1061,1062,1063,1064,1065,1066,1067,1068,1069,1070,1071,1072,1073,1074,1075,1076,1077,1078,1079,1080,1081,1082,1083,1084,1085,1086,1087,1088,1089,1090,1091,1092,1093,1094,1095,1096,1097,1098,1099,1100,1101,1102,1103,1104,1105,1106,1107,1108,1109,1110,1111,1112,1113,1114,1115,1116,1117,1118,1119,1120,1121,1122,1123,1124,1125,1126,1127,1128,1129,1130,1131,1132,1133,1134,1135,1136,1137,1138,1139,1140,1141,1142,1143,1144,1145,1146,1147,1148,1149,1150,1151,1152,1153,1154,1155,1156,1157,1158,1159,1160,1161,1162,1163,1164,1165,1166,1167,1168,1169,1170,1171,1172,1173,1174,1175,1176,1177,1178,1179,1180,1181,1182,1183,1184,1185,1186,1187,1188,1189,1190,1191,1192,1193,1194,1195,1196,1197,1198,1199,1200,1201,1202,1203,1204,1205,1206,1207,1208,1209,1210,1211,1212,1213,1214,1215,1216,1217,1218,1219,1220,1221,1222,1223,1224,1225,1226,1227,1228,1229,1230,1231,1232,1233,1234,1235,1236,1237,1238,1239,1240,1241,1242,1243,1244,1245,1246,1247,1248,1249,1250,1251,1252,1253,1254,1255,1256,1257,1258,1259,1260,1261,1262,1263,1264,1265,1266,1267,1268,1269,1270,1271,1272,1273,1274,1275,1276,1277,1278,1279,1280,1281,1282,1283,1284,1285,1286,1287,1288,1289,1290,1291,1292,1293,1294,1295,1296,1297,1298,1299,1300,1301,1302,1303,1304,1305,1306,1307,1308,1309,1310,1311,1312,1313,1314,1315,1316,1317,1318,1319,1320,1321,1322,1323,1324,1325,1326,1327,1328,1329,1330,1331,1332,1333,1334,1335,1336,1337,1338,1339,1340,1341,1342,1343,1344,1345,1346,1347,1348,1349,1350,1351,1352,1353,1354,1355,1356,1357,1358,1359,1360,1361,1362,1363,1364,1365,1366,1367,1368,1369,1370,1371,1372,1373,1374,1375,1376,1377,1378,1379,1380,1381,1382,1383,1384,1385,1386,1387,1388,1389,1390,1391,1392,1393,1394,1395,1396,1397,1398,1399,1400,1401,1402,1403,1404,1405,1406,1407,1408,1409,1410,1411,1412,1413,1414,1415,1416,1417,1418,1419,1420,1421,1422,1423,1424,1425,1426,1427,1428,1429,1430,1431,1432,1433,1434,1435,1436,1437,1438,1439,1440,1441,1442,1443,1444,1445,1446,1447,1448,1449,1450,1451,1452,1453,1454,1455,1456,1457,1458,1459,1460,1461,1462,1463,1464,1465,1466,1467,1468,1469,1470,1471,1472,1473,1474,1475,1476,1477,1478,1479,1480,1481,1482,1483,1484,1485,1486,1487,1488,1489,1490,1491,1492,1493,1494,1495,1496,1497,1498,1499,1500', '/api/v2/probes/?id__in=1501,1502,1503,1504,1505,1506,1507,1508,1509,1510,1511,1512,1513,1514,1515,1516,1517,1518,1519,1520,1521,1522,1523,1524,1525,1526,1527,1528,1529,1530,1531,1532,1533,1534,1535,1536,1537,1538,1539,1540,1541,1542,1543,1544,1545,1546,1547,1548,1549,1550,1551,1552,1553,1554,1555,1556,1557,1558,1559,1560,1561,1562,1563,1564,1565,1566,1567,1568,1569,1570,1571,1572,1573,1574,1575,1576,1577,1578,1579,1580,1581,1582,1583,1584,1585,1586,1587,1588,1589,1590,1591,1592,1593,1594,1595,1596,1597,1598,1599,1600,1601,1602,1603,1604,1605,1606,1607,1608,1609,1610,1611,1612,1613,1614,1615,1616,1617,1618,1619,1620,1621,1622,1623,1624,1625,1626,1627,1628,1629,1630,1631,1632,1633,1634,1635,1636,1637,1638,1639,1640,1641,1642,1643,1644,1645,1646,1647,1648,1649,1650,1651,1652,1653,1654,1655,1656,1657,1658,1659,1660,1661,1662,1663,1664,1665,1666,1667,1668,1669,1670,1671,1672,1673,1674,1675,1676,1677,1678,1679,1680,1681,1682,1683,1684,1685,1686,1687,1688,1689,1690,1691,1692,1693,1694,1695,1696,1697,1698,1699,1700,1701,1702,1703,1704,1705,1706,1707,1708,1709,1710,1711,1712,1713,1714,1715,1716,1717,1718,1719,1720,1721,1722,1723,1724,1725,1726,1727,1728,1729,1730,1731,1732,1733,1734,1735,1736,1737,1738,1739,1740,1741,1742,1743,1744,1745,1746,1747,1748,1749,1750,1751,1752,1753,1754,1755,1756,1757,1758,1759,1760,1761,1762,1763,1764,1765,1766,1767,1768,1769,1770,1771,1772,1773,1774,1775,1776,1777,1778,1779,1780,1781,1782,1783,1784,1785,1786,1787,1788,1789,1790,1791,1792,1793,1794,1795,1796,1797,1798,1799,1800,1801,1802,1803,1804,1805,1806,1807,1808,1809,1810,1811,1812,1813,1814,1815,1816,1817,1818,1819,1820,1821,1822,1823,1824,1825,1826,1827,1828,1829,1830,1831,1832,1833,1834,1835,1836,1837,1838,1839,1840,1841,1842,1843,1844,1845,1846,1847,1848,1849,1850,1851,1852,1853,1854,1855,1856,1857,1858,1859,1860,1861,1862,1863,1864,1865,1866,1867,1868,1869,1870,1871,1872,1873,1874,1875,1876,1877,1878,1879,1880,1881,1882,1883,1884,1885,1886,1887,1888,1889,1890,1891,1892,1893,1894,1895,1896,1897,1898,1899,1900,1901,1902,1903,1904,1905,1906,1907,1908,1909,1910,1911,1912,1913,1914,1915,1916,1917,1918,1919,1920,1921,1922,1923,1924,1925,1926,1927,1928,1929,1930,1931,1932,1933,1934,1935,1936,1937,1938,1939,1940,1941,1942,1943,1944,1945,1946,1947,1948,1949,1950,1951,1952,1953,1954,1955,1956,1957,1958,1959,1960,1961,1962,1963,1964,1965,1966,1967,1968,1969,1970,1971,1972,1973,1974,1975,1976,1977,1978,1979,1980,1981,1982,1983,1984,1985,1986,1987,1988,1989,1990,1991,1992,1993,1994,1995,1996,1997,1998,1999'] self.assertEqual(r.split_urls, expected_list) def test_sane_output(self): arequest = mock.patch('ripe.atlas.cousteau.request.AtlasRequest.get').start() arequest.return_value = True, { "count": "3", "next": None, "results": [ { "address_v4": None, "address_v6": None, "asn_v4": None, "asn_v6": None, "country_code": "GR", "id": 90, "is_anchor": False, "is_public": False, "prefix_v4": None, "prefix_v6": None, "status": 3, "tags": [ "home", "nat", ], "latitude": 37.4675, "longitude": 22.4015, "status_name": "Abandoned", "status_since": 1376578323 }, { "asn_v4": 3329, "asn_v6": None, "country_code": "GR", "id": 268, "is_anchor": False, "is_public": False, "prefix_v6": None, "status": 1, "tags": [ "system-ipv6-ula", "system-ipv4-rfc1918" ], "latitude": 40.6415, "longitude": 22.9405, "status_name": "Connected", "status_since": 1433248709 } ] } probe_generator = ProbeRequest(**{}) probes_list = list(probe_generator) expected_value = [ { "address_v4": None, "address_v6": None, "asn_v4": None, "asn_v6": None, "country_code": "GR", "id": 90, "is_anchor": False, "is_public": False, "prefix_v4": None, "prefix_v6": None, "status": 3, "tags": [ "home", "nat", ], "latitude": 37.4675, "longitude": 22.4015, "status_name": "Abandoned", "status_since": 1376578323 }, { "asn_v4": 3329, "asn_v6": None, "country_code": "GR", "id": 268, "is_anchor": False, "is_public": False, "prefix_v6": None, "status": 1, "tags": [ "system-ipv6-ula", "system-ipv4-rfc1918" ], "latitude": 40.6415, "longitude": 22.9405, "status_name": "Connected", "status_since": 1433248709 } ] self.assertEqual(probes_list, expected_value) self.assertEqual(probe_generator.total_count, 3) def test_wrong_api_output(self): arequest = mock.patch('ripe.atlas.cousteau.request.AtlasRequest.get').start() arequest.return_value = True, {} probe_generator = ProbeRequest(**{}) probes_list = list(probe_generator) expected_value = [] self.assertEqual(probes_list, expected_value) self.assertEqual(probe_generator.total_count, 0) def test_semisane_output(self): arequest = mock.patch('ripe.atlas.cousteau.request.AtlasRequest.get').start() first_get_resp = (True, { "count": "6", "next": "blaaaaaah", "results": [ { "address_v4": None, "address_v6": None, "asn_v4": None, "asn_v6": None, "country_code": "GR", "id": 90, "is_anchor": False, "is_public": False, "prefix_v4": None, "prefix_v6": None, "status": 3, "tags": [ "home", "nat", ], "latitude": 37.4675, "longitude": 22.4015, "status_name": "Abandoned", "status_since": 1376578323 }, { "asn_v4": 3329, "asn_v6": None, "country_code": "GR", "id": 268, "is_anchor": False, "is_public": False, "prefix_v6": None, "status": 1, "tags": [ "system-ipv6-ula", "system-ipv4-rfc1918" ], "latitude": 40.6415, "longitude": 22.9405, "status_name": "Connected", "status_since": 1433248709 } ] }) second_get_resp = (True, { "count": "5", "next": None, "results": [ { "address_v4": None, "address_v6": None, "asn_v4": None, "asn_v6": None, "country_code": "GR", "id": 99, "is_anchor": False, "is_public": False, "prefix_v4": None, "prefix_v6": None, "status": 3, "tags": [ "home", "nat", ], "latitude": 37.4675, "longitude": 22.4015, "status_name": "Abandoned", "status_since": 1376578323 }, { "asn_v4": 3329, "asn_v6": None, "country_code": "GR", "id": 269, "is_anchor": False, "is_public": False, "prefix_v6": None, "status": 1, "tags": [ "system-ipv6-ula", "system-ipv4-rfc1918" ], "latitude": 40.6415, "longitude": 22.9405, "status_name": "Connected", "status_since": 1433248709 } ] }) arequest.side_effect = [first_get_resp, second_get_resp] probe_generator = ProbeRequest(**{}) probes_list = list(probe_generator) expected_value = [ { "address_v4": None, "address_v6": None, "asn_v4": None, "asn_v6": None, "country_code": "GR", "id": 90, "is_anchor": False, "is_public": False, "prefix_v4": None, "prefix_v6": None, "status": 3, "tags": [ "home", "nat", ], "latitude": 37.4675, "longitude": 22.4015, "status_name": "Abandoned", "status_since": 1376578323 }, { "asn_v4": 3329, "asn_v6": None, "country_code": "GR", "id": 268, "is_anchor": False, "is_public": False, "prefix_v6": None, "status": 1, "tags": [ "system-ipv6-ula", "system-ipv4-rfc1918" ], "latitude": 40.6415, "longitude": 22.9405, "status_name": "Connected", "status_since": 1433248709 }, { "address_v4": None, "address_v6": None, "asn_v4": None, "asn_v6": None, "country_code": "GR", "id": 99, "is_anchor": False, "is_public": False, "prefix_v4": None, "prefix_v6": None, "status": 3, "tags": [ "home", "nat", ], "latitude": 37.4675, "longitude": 22.4015, "status_name": "Abandoned", "status_since": 1376578323 }, { "asn_v4": 3329, "asn_v6": None, "country_code": "GR", "id": 269, "is_anchor": False, "is_public": False, "prefix_v6": None, "status": 1, "tags": [ "system-ipv6-ula", "system-ipv4-rfc1918" ], "latitude": 40.6415, "longitude": 22.9405, "status_name": "Connected", "status_since": 1433248709 } ] self.assertEqual(probes_list, expected_value) self.assertEqual(probe_generator.total_count, 6) def test_user_agent(self): self.assertEqual(RequestGenerator()._user_agent, None) self.assertEqual(RequestGenerator(user_agent="x")._user_agent, "x") def tearDown(self): mock.patch.stopall() class TestProbeRequestGenerator(TestCase): def test_url(self): gen = ProbeRequest() self.assertEquals(gen.url, "/api/v2/probes/") def test_id_filter(self): gen = ProbeRequest() self.assertEquals(gen.id_filter, "id__in") class TestMeasurementRequestGenerator(TestCase): def test_url(self): gen = MeasurementRequest(return_objects=True) self.assertEquals(gen.url, "/api/v2/measurements/") def test_id_filter(self): gen = MeasurementRequest() self.assertEquals(gen.id_filter, "id__in") class TestAnchorRequestGenerator(TestCase): def test_return_objects(self): gen = AnchorRequest(return_objects=True) self.assertFalse(gen.return_objects) def test_url(self): gen = AnchorRequest(return_objects=True) self.assertEquals(gen.url, "/api/v2/anchors/") def test_id_filter(self): gen = AnchorRequest() self.assertEquals(gen.id_filter, "id__in") ripe-atlas-cousteau-1.4.2/tests/test_api_meta_data.py000066400000000000000000000223121325447220000227270ustar00rootroot00000000000000# Copyright (c) 2015 RIPE NCC # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # Python 3.4+ comes with mock in unittest try: from unittest import mock except ImportError: import mock from unittest import TestCase from datetime import datetime from dateutil.tz import tzutc from ripe.atlas.cousteau import Probe, Measurement from ripe.atlas.cousteau.exceptions import APIResponseError class TestProbeRepresentation(TestCase): def test_sane_response(self): with mock.patch('ripe.atlas.cousteau.request.AtlasRequest.get') as request_mock: resp = { "address_v4": "62.194", "address_v6": None, "asn_v4": 68, "asn_v6": None, "country_code": "ND", "id": 1, "is_anchor": False, "is_public": False, "prefix_v4": "62.194.0.0/16", "prefix_v6": None, "tags": ["cable"], "geometry": { "type": "Point", "coordinates": [4.8875, 52.3875] }, "status": { "since": "2015-09-28T13:25:16", "id": 1, "name": "Connected" } } request_mock.return_value = True, resp probe = Probe(id=1) self.assertEqual(probe.meta_data, resp) self.assertEqual(probe.country_code, "ND") self.assertEqual(probe.address_v4, "62.194") self.assertEqual(probe.address_v6, None) self.assertEqual(probe.asn_v4, 68) self.assertEqual(probe.asn_v6, None) self.assertEqual(probe.is_anchor, False) self.assertEqual(probe.is_public, False) self.assertEqual(probe.prefix_v4, "62.194.0.0/16") self.assertEqual(probe.prefix_v6, None) self.assertEqual(probe.status, "Connected") self.assertEqual(probe.tags, ["cable"]) self.assertEqual(probe.prefix_v6, None) self.assertEqual(probe.geometry, {"type": "Point", "coordinates": [4.8875, 52.3875]}) def test_error_response(self): with mock.patch('ripe.atlas.cousteau.request.AtlasRequest.get') as request_mock: request_mock.return_value = False, {} self.assertRaises(APIResponseError, lambda: Probe(id=1)) def test_user_agent(self): paths = { "fetch": "ripe.atlas.cousteau.Probe._fetch_meta_data", "populate": "ripe.atlas.cousteau.Probe._populate_data", } with mock.patch(paths["fetch"]) as fetch: fetch.return_value = True with mock.patch(paths["populate"]): self.assertEqual(Probe(id=1)._user_agent, None) self.assertEqual( Probe(id=1, user_agent=None)._user_agent, None) self.assertEqual( Probe(id=1, user_agent="w00t")._user_agent, "w00t") def test_fields(self): with mock.patch('ripe.atlas.cousteau.request.AtlasRequest.get') as request_mock: request_mock.return_value = True, {} Probe(id=1, fields=["probes"]) self.assertEquals(request_mock.call_args[1], {"fields": "probes"}) Probe(id=1, fields=["probes", "data"]) self.assertEquals(request_mock.call_args[1], {"fields": "probes,data"}) Probe(id=1, fields="probes,data") self.assertEquals(request_mock.call_args[1], {"fields": "probes,data"}) Probe(id=1, fields=1) self.assertEquals(request_mock.call_args[1], {}) class TestMeasurementRepresentation(TestCase): def setUp(self): self.resp = { "af": 4, "target_ip": "202.73.56.70", "target_asn": 9255, "target": "blaaaah", "msm_id": 2310448, "description": "Blaaaaaaaaaah", "is_oneoff": True, "is_public": True, "interval": 1800, "creation_time": 1439379910, "resolve_on_probe": False, "start_time": 1439379910, "stop_time": 1439380502, "status": {"id": 4, "name": "Stopped"}, "resolved_ips": ["202.73.56.70"], "type": {"id": 8, "name": "http", "af": 4}, "result": "/api/v1/measurement/2310448/result/" } def test_sane_response(self): with mock.patch('ripe.atlas.cousteau.request.AtlasRequest.get') as request_mock: request_mock.return_value = True, self.resp measurement = Measurement(id=1) self.assertEqual(measurement.meta_data, self.resp) self.assertEqual(measurement.protocol, 4) self.assertEqual(measurement.target_ip, "202.73.56.70") self.assertEqual(measurement.target_asn, 9255) self.assertEqual(measurement.target, "blaaaah") self.assertEqual(measurement.description, "Blaaaaaaaaaah") self.assertEqual(measurement.is_oneoff, True) self.assertEqual(measurement.is_public, True) self.assertEqual(measurement.interval, 1800) self.assertEqual(measurement.status, "Stopped") self.assertEqual(measurement.creation_time, datetime.utcfromtimestamp(1439379910).replace(tzinfo=tzutc())) self.assertEqual(measurement.start_time, datetime.utcfromtimestamp(1439379910).replace(tzinfo=tzutc())) self.assertEqual(measurement.stop_time, datetime.utcfromtimestamp(1439380502).replace(tzinfo=tzutc())) self.assertEqual(measurement.type, "HTTP") self.assertEqual(measurement.result_url, "/api/v1/measurement/2310448/result/") def test_type1(self): """Tests format of the type key in response, soon to be deprecated.""" with mock.patch('ripe.atlas.cousteau.request.AtlasRequest.get') as request_mock: self.resp["type"] = {"id": 8, "name": "dns", "af": 4} request_mock.return_value = True, self.resp measurement = Measurement(id=1) self.assertEqual(measurement.type, "DNS") self.resp["type"] = {} request_mock.return_value = True, self.resp measurement = Measurement(id=1) self.assertEqual(measurement.type, "") def test_type2(self): """Tests new format of the type key in response, soon to be enabled.""" with mock.patch('ripe.atlas.cousteau.request.AtlasRequest.get') as request_mock: self.resp["type"] = "dns" request_mock.return_value = True, self.resp measurement = Measurement(id=1) self.assertEqual(measurement.type, "dns") def test_error_response(self): with mock.patch('ripe.atlas.cousteau.request.AtlasRequest.get') as request_mock: request_mock.return_value = False, {} self.assertRaises(APIResponseError, lambda: Measurement(id=1)) def test_user_agent(self): paths = { "fetch": "ripe.atlas.cousteau.Measurement._fetch_meta_data", "populate": "ripe.atlas.cousteau.Measurement._populate_data", } with mock.patch(paths["fetch"]) as fetch: fetch.return_value = True with mock.patch(paths["populate"]): self.assertEqual(Measurement(id=1)._user_agent, None) self.assertEqual( Measurement(id=1, user_agent=None)._user_agent, None) self.assertEqual( Measurement(id=1, user_agent="w00t")._user_agent, "w00t") def test_fields(self): with mock.patch('ripe.atlas.cousteau.request.AtlasRequest.get') as request_mock: request_mock.return_value = True, {} Measurement(id=1, fields=["probes"]) self.assertEquals(request_mock.call_args[1], {"fields": "probes"}) Measurement(id=1, fields=["probes", "data"]) self.assertEquals(request_mock.call_args[1], {"fields": "probes,data"}) Measurement(id=1, fields="probes,data") self.assertEquals(request_mock.call_args[1], {"fields": "probes,data"}) Measurement(id=1, fields=1) self.assertEquals(request_mock.call_args[1], {}) def test_populate_times(self): with mock.patch('ripe.atlas.cousteau.request.AtlasRequest.get') as request_mock: del self.resp["stop_time"] del self.resp["creation_time"] del self.resp["start_time"] request_mock.return_value = True, self.resp measurement = Measurement(id=1) self.assertEqual(measurement.stop_time, None) self.assertEqual(measurement.start_time, None) self.assertEqual(measurement.creation_time, None) ripe-atlas-cousteau-1.4.2/tests/test_measurement_types.py000066400000000000000000000076201325447220000237350ustar00rootroot00000000000000# Copyright (c) 2015 RIPE NCC # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . """File containing the nose tests""" import unittest from ripe.atlas.cousteau import ( Ping, Traceroute, Dns, Sslcert, Ntp, Http ) class TestMeasurementTypes(unittest.TestCase): def test_ping(self): """Unittest for Ping class""" post_body = Ping(**{ "target": "www.google.fr", "af": 4, "description": "testing", "prefer_anchors": True }).build_api_struct() expected_output = { 'description': 'testing', 'af': 4, 'type': 'ping', 'target': 'www.google.fr', 'prefer_anchors': True } self.assertEqual(post_body, expected_output) def test_dns(self): """Unittest for Dns class""" post_body = Dns( **{ "target": "k.root-servers.net", "af": 4, "description": "testing", "query_type": "SOA", "query_class": "IN", "query_argument": "nl", "retry": 6 } ).build_api_struct() expected_output = { 'query_class': 'IN', 'retry': 6, 'description': 'testing', 'af': 4, 'query_argument': 'nl', 'query_type': 'SOA', 'type': 'dns', 'target': 'k.root-servers.net' } self.assertEqual(post_body, expected_output) def test_traceroute(self): """Unittest for Traceroute class""" post_body = Traceroute(**{ "af": 4, "target": 'www.ripe.net', "description": 'testing', "protocol": "ICMP", "prefer_anchors": True, }).build_api_struct() expected_output = { 'protocol': 'ICMP', 'description': 'testing', 'prefer_anchors': True, 'af': 4, 'type': 'traceroute', 'target': 'www.ripe.net' } self.assertEqual(post_body, expected_output) def test_sslcert(self): """Unittest for Sslcert class""" post_body = Sslcert(**{ "af": 4, "target": 'www.ripe.net', "description": 'testing', "prefer_anchors": True, }).build_api_struct() expected_output = { 'description': 'testing', 'af': 4, 'type': 'sslcert', 'target': 'www.ripe.net', 'prefer_anchors': True } self.assertEqual(post_body, expected_output) def test_ntpcert(self): """Unittest for Ntp class""" post_body = Ntp(**{ "af": 4, "target": 'www.ripe.net', "description": 'testing', "prefer_anchors": True, }).build_api_struct() expected_output = { 'description': 'testing', 'af': 4, 'type': 'ntp', 'target': 'www.ripe.net', 'prefer_anchors': True } self.assertEqual(post_body, expected_output) def test_http(self): """Unittest for HTTP class""" post_body = Http(**{ "af": 4, "target": 'www.ripe.net', "description": 'testing', "prefer_anchors": True, }).build_api_struct() expected_output = { 'description': 'testing', 'af': 4, 'type': 'http', 'target': 'www.ripe.net', 'prefer_anchors': True } self.assertEqual(post_body, expected_output) ripe-atlas-cousteau-1.4.2/tests/test_measurements.py000066400000000000000000000051361325447220000226740ustar00rootroot00000000000000# Copyright (c) 2015 RIPE NCC # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import unittest from jsonschema import validate from ripe.atlas.cousteau.measurement import ( MalFormattedMeasurement, AtlasMeasurement ) from . import definitions_schema class TestAtlasMeasurement(unittest.TestCase): def setUp(self): kwargs = {"target": "www.google.gr", "af": 4} self.measurement = AtlasMeasurement(**kwargs) self.measurement._init(**kwargs) def test_add_option(self): self.assertRaises(TypeError, lambda: self.measurement.add_option("3")) self.assertRaises(TypeError, lambda: self.measurement.add_option(3)) self.assertRaises( TypeError, lambda: self.measurement.add_option(["3"]) ) self.assertRaises( TypeError, lambda: self.measurement.add_option(*["3"]) ) self.measurement.add_option(**{"test": "test"}) self.assertEqual(self.measurement.test, "test") def test_init_required_options(self): self.measurement._init_required_options( **{"af": 4, "description": "test", "crap": "test"} ) self.assertEqual(self.measurement.af, 4) self.assertEqual(self.measurement.description, "test") self.assertRaises( AttributeError, lambda: getattr(self.measurement, "crap") ) def test_clean(self): self.assertRaises( MalFormattedMeasurement, lambda: self.measurement.clean() ) self.measurement.measurement_type = "test" self.measurement.description = "test" self.measurement.clean() def test_build_api_struct(self): output = { "type": "ping", "target": "www.google.gr", "af": 4, "description": "test" } self.measurement.description = "test" self.measurement.measurement_type = "ping" self.assertEqual(self.measurement.build_api_struct(), output) validate(self.measurement.build_api_struct(), definitions_schema) ripe-atlas-cousteau-1.4.2/tests/test_real_server.py000066400000000000000000000215051325447220000224730ustar00rootroot00000000000000# Copyright (c) 2015 RIPE NCC # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import os import unittest from datetime import datetime, timedelta from collections import namedtuple from nose.exc import SkipTest from ripe.atlas.cousteau import ( AtlasSource, AtlasChangeSource, AtlasRequest, AtlasCreateRequest, AtlasChangeRequest, Ping, Dns, AtlasStopRequest, AtlasResultsRequest, ProbeRequest, MeasurementRequest, Probe, Measurement, AtlasStream, Ntp, Sslcert, Http, Traceroute, AnchorRequest ) class TestRealServer(unittest.TestCase): def setUp(self): self.server = os.environ.get('ATLAS_SERVER', "") self.create_key = os.environ.get('CREATE_KEY', "") self.change_key = os.environ.get('CHANGE_KEY', "") self.delete_key = os.environ.get('DELETE_KEY', "") self.delete_msm = None def test_create_delete_request(self): """Unittest for Atlas create and delete request""" if self.server == "": raise SkipTest source = AtlasSource(**{"type": "area", "value": "WW", "requested": 38}) ping = Ping(**{ "target": "www.ripe.net", "af": 4, "description": "Cousteau testing", "prefer_anchors": True }) traceroute = Traceroute(**{ "target": "www.google.fr", "af": 4, "protocol": "UDP", "description": "Cousteau testing", "dont_fragment": True }) dns = Dns(**{ "target": "k.root-servers.net", "af": 4, "description": "Cousteau testing", "query_type": "SOA", "query_class": "IN", "query_argument": "nl", "retry": 6 }) ntp = Ntp(**{ "target": "www.ripe.net", "af": 4, "description": "Cousteau testing", "timeout": 1000 }) ssl = Sslcert(**{ "target": "www.ripe.net", "af": 4, "description": "Cousteau testing", }) http = Http(**{ "target": "www.ripe.net", "af": 4, "description": "Cousteau testing", }) stop = datetime.utcnow() + timedelta(minutes=220) request = AtlasCreateRequest( **{ "verify": False, "stop_time": stop, "key": self.create_key, "server": self.server, "measurements": [ping, traceroute, dns, ntp, ssl, http], "sources": [source] } ) result = namedtuple('Result', 'success response') (result.success, result.response) = request.create() print(result.response) self.assertTrue(result.success) self.delete_msm = result.response["measurements"][0] self.assertTrue(result.success) # Unittest for Atlas delete request if self.server == "": raise SkipTest kwargs = {"verify": False, "msm_id": self.delete_msm, "key": self.delete_key, "server": self.server} request = AtlasStopRequest(**kwargs) result = namedtuple('Result', 'success response') (result.success, result.response) = request.create() print(result.response) self.assertTrue(result.success) def test_change_request(self): """Unittest for Atlas change request""" if self.server == "": raise SkipTest remove = AtlasChangeSource(**{ "value": "6001", "requested": 1, "action": "remove", "type": "probes" }) add = AtlasChangeSource(**{ "value": "6002", "requested": 1, "action": "add", "type": "probes" }) request = AtlasChangeRequest( **{ "key": self.change_key, "verify": False, "msm_id": 1000032, "server": self.server, "sources": [add, remove] } ) result = namedtuple('Result', 'success response') (result.success, result.response) = request.create() print(result.response) self.assertTrue(result.success) def test_result_request(self): """Unittest for Atlas results request""" if self.server == "": raise SkipTest kwargs = { "msm_id": 1000032, "start": datetime(2011, 11, 21), "stop": datetime(2011, 11, 22), "verify": False, "probe_ids": [743, 630] } result = namedtuple('Result', 'success response') (result.success, result.response) = AtlasResultsRequest(**kwargs).create() print(result.success, result.response) self.assertTrue(result.response) self.assertTrue(result.success) def test_probe_request(self): """Unittest for ProbeRequest""" if self.server == "": raise SkipTest filters = {"tags": "NAT", "country_code": "NL", "asn_v4": "3333"} probes = ProbeRequest(**filters) probes_list = list(probes) self.assertTrue(probes_list) self.assertTrue(probes.total_count) def test_measurement_request(self): """Unittest for MeasurementRequest""" if self.server == "": raise SkipTest filters = {"id__lt": 1000010, "id__gt": 1000002} measurements = MeasurementRequest(**filters) measurements_list = list(measurements) self.assertTrue(measurements_list) self.assertTrue(measurements.total_count) def test_anchor_request(self): """Unittest for AnchorRequest""" if self.server == "": raise SkipTest anchors = AnchorRequest() anchors_list = list(anchors) self.assertTrue(anchors_list) self.assertTrue(anchors.total_count) def test_probe_repr_request(self): """Unittest for Probe representation request""" if self.server == "": raise SkipTest Probe(id=6001) def test_measurement_repr_request(self): """Unittest for Measurement representation request""" if self.server == "": raise SkipTest Measurement(id=1000032, server=self.server, verify=False) def test_stream_results(self): """Unittest for Atlas results request.""" if self.server == "": raise SkipTest results = [] def on_result_response(*args): """ Function that will be called every time we receive a new result. Args is a tuple, so you should use args[0] to access the real message. """ results.append(args[0]) atlas_stream = AtlasStream() atlas_stream.connect() channel = "result" atlas_stream.bind_channel(channel, on_result_response) stream_parameters = {"msm": 1001} atlas_stream.start_stream(stream_type="result", **stream_parameters) atlas_stream.timeout(seconds=5) atlas_stream.disconnect() self.assertNotEqual(results, []) def test_stream_probe(self): """Unittest for Atlas probe connections request.""" if self.server == "": raise SkipTest results = [] def on_result_response(*args): """ Function that will be called every time we receive a new event. Args is a tuple, so you should use args[0] to access the real message. """ results.append(args[0]) atlas_stream = AtlasStream() atlas_stream.connect() channel = "atlas_probestatus" atlas_stream.bind_channel(channel, on_result_response) stream_parameters = {"enrichProbes": True} atlas_stream.start_stream(stream_type="probestatus", **stream_parameters) atlas_stream.timeout(seconds=30) atlas_stream.disconnect() self.assertNotEqual(results, []) def test_get_request(self): """Unittest for Atlas get request""" if self.server == "": raise SkipTest request = AtlasRequest( **{ "verify": False, "url_path": "/api/v2/anchors" } ) result = namedtuple('Result', 'success response') (result.success, result.response) = request.get() print(result.success, result.response) self.assertTrue(result.response["results"]) self.assertTrue(result.success) ripe-atlas-cousteau-1.4.2/tests/test_requests.py000066400000000000000000000402161325447220000220350ustar00rootroot00000000000000# Copyright (c) 2015 RIPE NCC # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # Python 3.4+ comes with mock in unittest try: from unittest import mock except ImportError: import mock from unittest import TestCase import requests from datetime import datetime from jsonschema import validate from ripe.atlas.cousteau.version import __version__ from ripe.atlas.cousteau import ( Ping, AtlasSource, AtlasChangeSource, AtlasCreateRequest, AtlasChangeRequest, AtlasLatestRequest, AtlasResultsRequest, AtlasRequest ) from . import post_data_create_schema, post_data_change_schema class FakeResponse(object): def __init__(self, json_return={}, ok=True): self.json_return = json_return self.ok = ok self.text = "testing" def json(self): return self.json_return class FakeErrorResponse(FakeResponse): def json(self): raise ValueError("json breaks") class TestAtlasRequest(TestCase): def setUp(self): self.request = AtlasRequest(**{ "key": "blaaaa", "server": "test", "url_path": "testing" }) def test_headers(self): """Tests header fields of the request.""" expected_output = { "User-Agent": "RIPE ATLAS Cousteau v{0}".format(__version__), "Content-Type": "application/json", "Accept": "application/json" } self.assertEqual(expected_output, self.request.get_headers()) def test_http_method_args(self): """Tests initial args that will be passed later to HTTP method.""" expected_output = { "params": {"key": "blaaaa"}, "verify": True, "headers": { "User-Agent": "RIPE ATLAS Cousteau v{0}".format(__version__), "Content-Type": "application/json", "Accept": "application/json" }, "proxies": {}, } self.assertEqual(expected_output, self.request.http_method_args) def test_get_method(self): """Tests GET reuest method""" extra_params = {"bull": "shit", "cow": "shit", "horse": "shit"} expected_args = { "params": { "key": "blaaaa", "bull": "shit", "cow": "shit", "horse": "shit" }, "verify": True, "headers": { "User-Agent": "RIPE ATLAS Cousteau v{0}".format(__version__), "Content-Type": "application/json", "Accept": "application/json" }, "proxies": {}, } with mock.patch("ripe.atlas.cousteau.request.AtlasRequest.http_method") as mock_get: mock_get.return_value = True self.request.get(**extra_params) self.assertEqual(self.request.http_method_args, expected_args) def test_url_build(self): """Tests build of the url of the request.""" self.request.build_url() self.assertEqual(self.request.url, "https://testtesting") def test_success_http_method(self): """Tests the main http method function of the request in case of success""" with mock.patch("ripe.atlas.cousteau.AtlasRequest.get_http_method") as mock_get: fake = FakeResponse(json_return={"blaaa": "b"}) mock_get.return_value = fake self.assertEqual( self.request.http_method("GET"), (True, {"blaaa": "b"}) ) fake_error = FakeErrorResponse() mock_get.return_value = fake_error self.assertEqual( self.request.http_method("GET"), (True, "testing") ) def test_not_success_http_method(self): """Tests the main http method function of the request in case of fail""" with mock.patch("ripe.atlas.cousteau.AtlasRequest.get_http_method") as mock_get: fake = FakeResponse(json_return={"blaaa": "b"}, ok=False) mock_get.return_value = fake self.assertEqual( self.request.http_method("GET"), (False, {"blaaa": "b"}) ) fake_error = FakeErrorResponse(ok=False) mock_get.return_value = fake_error self.assertEqual( self.request.http_method("GET"), (False, "testing") ) def test_exception_http_method(self): """Tests the main http method function of the request in case of fail""" with mock.patch("ripe.atlas.cousteau.AtlasRequest.get_http_method") as mock_get: mock_get.side_effect = requests.exceptions.RequestException("excargs") self.assertEqual( self.request.http_method("GET"), (False, ("excargs",)) ) def test_user_agent(self): with mock.patch("ripe.atlas.cousteau.request.__version__", 999): standard = "RIPE ATLAS Cousteau v999" self.assertEqual(AtlasRequest().http_agent, standard) self.assertEqual(AtlasRequest(user_agent=None).http_agent, standard) self.assertEqual(AtlasRequest(user_agent="w00t").http_agent, "w00t") class TestAtlasCreateRequest(TestCase): def setUp(self): self.create_source = AtlasSource( **{"type": "area", "value": "WW", "requested": 3} ) self.measurement = Ping(**{ "target": "testing", "af": 6, "description": "testing" }) self.request = AtlasCreateRequest(**{ "start_time": datetime(2015, 10, 16), "stop_time": 1445040000, "key": "path_to_key", "measurements": [self.measurement], "sources": [self.create_source], "is_oneoff": True, }) def test_construct_post_data(self): """Tests construction of past data""" self.request._construct_post_data() validate(self.request.post_data, post_data_create_schema) def test_post_method(self): """Tests POST reuest method""" self.maxDiff = None expected_args = { "json": { "definitions": [{ "af": 6, "description": "testing", "target": "testing", "type": "ping" }], "is_oneoff": True, "probes": [{"requested": 3, "type": "area", "value": "WW"}], "start_time": 1444953600, "stop_time": 1445040000 }, "params": {"key": "path_to_key"}, "verify": True, "headers": { "User-Agent": "RIPE ATLAS Cousteau v{0}".format(__version__), "Content-Type": "application/json", "Accept": "application/json" }, "proxies": {}, } with mock.patch("ripe.atlas.cousteau.request.AtlasRequest.http_method") as mock_get: self.request._construct_post_data() mock_get.return_value = True self.request.post() self.assertEqual(self.request.http_method_args, expected_args) def test_post_method_without_times(self): """Tests POST reuest method with a bill to address specified""" request = AtlasCreateRequest(**{ "key": "path_to_key", "measurements": [self.measurement], "sources": [self.create_source], }) self.maxDiff = None expected_args = { "json": { "definitions": [{ "af": 6, "description": "testing", "target": "testing", "type": "ping" }], "is_oneoff": False, "probes": [{"requested": 3, "type": "area", "value": "WW"}], }, "params": {"key": "path_to_key"}, "verify": True, "headers": { "User-Agent": "RIPE ATLAS Cousteau v{0}".format(__version__), "Content-Type": "application/json", "Accept": "application/json" }, "proxies": {}, } with mock.patch("ripe.atlas.cousteau.request.AtlasRequest.http_method") as mock_get: request._construct_post_data() mock_get.return_value = True request.post() self.assertEqual(request.http_method_args, expected_args) def test_post_method_with_bill_to(self): """Tests POST reuest method without any time specified""" request = AtlasCreateRequest(**{ "key": "path_to_key", "measurements": [self.measurement], "sources": [self.create_source], "bill_to": "billing@address" }) self.maxDiff = None expected_args = { "json": { "definitions": [{ "af": 6, "description": "testing", "target": "testing", "type": "ping" }], "is_oneoff": False, "probes": [{"requested": 3, "type": "area", "value": "WW"}], "bill_to": "billing@address", }, "params": {"key": "path_to_key"}, "verify": True, "headers": { "User-Agent": "RIPE ATLAS Cousteau v{0}".format(__version__), "Content-Type": "application/json", "Accept": "application/json" }, "proxies": {}, } with mock.patch("ripe.atlas.cousteau.request.AtlasRequest.http_method") as mock_get: request._construct_post_data() mock_get.return_value = True request.post() self.assertEqual(request.http_method_args, expected_args) class TestAtlasChangeRequest(TestCase): def setUp(self): change_source = AtlasChangeSource( **{"value": "WW", "requested": 3, "action": "add", "type": "area"} ) self.request = AtlasChangeRequest(**{ "msm_id": 1, "sources": [change_source] }) def test_construct_post_data(self): self.request._construct_post_data() validate(self.request.post_data, post_data_change_schema) class TestAtlasResultsRequest(TestCase): def test_url_path_and_params(self): request = AtlasResultsRequest(**{ "msm_id": 1000002, "start": "2011-11-27", "stop": "2011-11-27 01", "probe_ids": [1, 2, 3] }) self.assertEqual( request.url_path, "/api/v2/measurements/1000002/results" ) query_filters = request.http_method_args["params"] self.assertEqual( set(query_filters.keys()), set(["key", "stop", "start", "probe_ids"]) ) self.assertEqual(query_filters["start"], 1322352000) self.assertEqual(query_filters["stop"], 1322355600) self.assertEqual( query_filters["probe_ids"], "1,2,3" ) def test_probe_ids_query_params(self): """Tests probe_ids as query params for different entries""" request = AtlasResultsRequest(**{ "msm_id": 1000002, "probe_ids": [1, 2, 3] }) query_filters = request.http_method_args["params"] self.assertEqual( query_filters["probe_ids"], "1,2,3" ) request = AtlasResultsRequest(**{ "msm_id": 1000002, "probe_ids": "15, 2,3" }) query_filters = request.http_method_args["params"] self.assertEqual( query_filters["probe_ids"], "15, 2,3" ) request = AtlasResultsRequest(**{ "msm_id": 1000002, "probe_ids": 15 }) query_filters = request.http_method_args["params"] self.assertEqual( query_filters["probe_ids"], 15 ) def test_start_time_query_params(self): """Tests start time as query params for different entries""" request = AtlasResultsRequest(**{ "msm_id": 1000002, "start": "2011-11-27", }) query_filters = request.http_method_args["params"] self.assertEqual(query_filters["start"], 1322352000) request = AtlasResultsRequest(**{ "msm_id": 1000002, "start": "2011-11-27 01:01", }) query_filters = request.http_method_args["params"] self.assertEqual(query_filters["start"], 1322355660) request = AtlasResultsRequest(**{ "msm_id": 1000002, "start": 1322352000, }) query_filters = request.http_method_args["params"] self.assertEqual(query_filters["start"], 1322352000) request = AtlasResultsRequest(**{ "msm_id": 1000002, "start": datetime(2011, 11, 27) }) query_filters = request.http_method_args["params"] self.assertEqual(query_filters["start"], 1322352000) def test_stop_time_query_params(self): """Tests stop time as query params for different entries""" request = AtlasResultsRequest(**{ "msm_id": 1000002, "stop": "2011-11-27", }) query_filters = request.http_method_args["params"] self.assertEqual(query_filters["stop"], 1322352000) request = AtlasResultsRequest(**{ "msm_id": 1000002, "stop": "2011-11-27 01:01", }) query_filters = request.http_method_args["params"] self.assertEqual(query_filters["stop"], 1322355660) request = AtlasResultsRequest(**{ "msm_id": 1000002, "stop": 1322352000, }) query_filters = request.http_method_args["params"] self.assertEqual(query_filters["stop"], 1322352000) request = AtlasResultsRequest(**{ "msm_id": 1000002, "stop": datetime(2011, 11, 27) }) query_filters = request.http_method_args["params"] self.assertEqual(query_filters["stop"], 1322352000) class TestAtlasLatestRequest(TestCase): def test_url_path(self): """Tests construction of path.""" self.assertEqual( AtlasLatestRequest(msm_id=1001).url_path, "/api/v2/measurements/1001/latest" ) self.assertEqual( AtlasLatestRequest(msm_id=1002, probe_ids=[1, 2, 3]).url_path, "/api/v2/measurements/1002/latest" ) def test_query_params(self): """Tests construction of query parameters.""" self.assertEqual( AtlasLatestRequest( msm_id=1001, probe_ids=(1, 2, 3, 24) ).http_method_args["params"], {"key": None, "probe_ids": "1,2,3,24"} ) self.assertEqual( AtlasLatestRequest( msm_id=1001, probe_ids="1, 2, 3, 24" ).http_method_args["params"], {"key": None, "probe_ids": "1, 2, 3, 24"} ) class TestAtlasRequestCustomHeaders(TestCase): def setUp(self): self.create_source = AtlasSource( **{"type": "area", "value": "WW", "requested": 3} ) self.measurement = Ping(**{ "target": "testing", "af": 6, "description": "testing" }) self.request = AtlasCreateRequest(**{ "start_time": datetime(2015, 10, 16), "stop_time": 1445040000, "key": "path_to_key", "measurements": [self.measurement], "sources": [self.create_source], "is_oneoff": True, "headers": {"hello": "world"}, }) def test_custom_headers(self): expected_headers = { "Content-Type": "application/json", "hello": "world", "Accept": "application/json", "User-Agent": "RIPE ATLAS Cousteau v{0}".format(__version__) } self.assertEqual(self.request.get_headers(), expected_headers) ripe-atlas-cousteau-1.4.2/tests/test_source.py000066400000000000000000000171041325447220000214620ustar00rootroot00000000000000# Copyright (c) 2015 RIPE NCC # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import unittest from jsonschema import validate from ripe.atlas.cousteau import ( AtlasSource, AtlasChangeSource ) from ripe.atlas.cousteau.source import MalFormattedSource from . import probes_create_schema, probes_change_schema class TestAtlasSource(unittest.TestCase): def test_sane_type_attribute(self): """Test sane input for type attribute""" for stype in AtlasChangeSource.types_available: kwargs = {"requested": 5, "value": "test", "type": stype} AtlasSource(**kwargs) def test_wrong_type_attribute(self): """Test wrong input for type attribute""" kwargs = {"requested": 5, "value": "test", "type": "blaaaaaaa"} self.assertRaises( MalFormattedSource, lambda: AtlasSource(**kwargs) ) def test_clean(self): # all ok kwargs = {"requested": 5, "value": "test", "type": "msm"} source = AtlasSource(**kwargs) self.assertEqual(source.clean(), None) # value missing source.value = None self.assertRaises( MalFormattedSource, lambda: source.clean() ) # type missing kwargs = {"requested": 5, "value": "test"} self.assertRaises( MalFormattedSource, lambda: AtlasSource(**kwargs).clean() ) # requested missing source.value = "test" source.requested = None self.assertRaises( MalFormattedSource, lambda: source.clean() ) def test_build_api_struct(self): kwargs = {"requested": 5, "value": "test", "type": "msm"} source = AtlasSource(**kwargs) self.assertEqual(source.build_api_struct(), kwargs) validate(source.build_api_struct(), probes_create_schema) def test_set_tags(self): # all ok kwargs = { "requested": 5, "value": "test", "type": "msm", "tags": {"include": ["one", "two"], "exclude": ["one", "two"]}} source = AtlasSource(**kwargs) self.assertEqual(source.clean(), None) self.assertEqual( source.tags, {"include": ["one", "two"], "exclude": ["one", "two"]} ) # include missing kwargs = { "requested": 5, "value": "test", "type": "msm", "tags": {"exclude": ["one", "two"]} } source = AtlasSource(**kwargs) self.assertEqual(source.clean(), None) # exclude missing kwargs = { "requested": 5, "value": "test", "type": "msm", "tags": {"include": ["one", "two"]} } source = AtlasSource(**kwargs) self.assertEqual(source.clean(), None) # invalid tag type kwargs = { "requested": 5, "value": "test", "type": "msm", "tags": {"include": ["one", 2], "exclude": ["one", "two"]} } self.assertRaises(MalFormattedSource, lambda: AtlasSource(**kwargs)) # unknown element kwargs = { "requested": 5, "value": "test", "type": "msm", "tags": { "include": ["one", 2], "exclude": ["one", "two"], "unknown": "?" } } self.assertRaises(MalFormattedSource, lambda: AtlasSource(**kwargs)) def test_build_api_struct_with_tags(self): kwargs = { "requested": 5, "value": "test", "type": "msm", "tags": {"include": ["one", "two"], "exclude": ["one", "two"]} } source = AtlasSource(**kwargs) self.assertEqual(source.build_api_struct(), kwargs) validate(source.build_api_struct(), probes_create_schema) class TestAtlasChangeSource(unittest.TestCase): def test_setting_type(self): kwargs = { "requested": 5, "value": "test", "action": "add" } source = AtlasChangeSource(**kwargs) for source_type in ["area", "country", "prefix", "asn", "msm", "probes"]: self.assertEqual(setattr(source, "type", source_type), None) kwargs = { "requested": 5, "value": "test", "action": "remove" } source = AtlasChangeSource(**kwargs) for source_type in ["area", "country", "prefix", "asn", "msm"]: self.assertRaises( MalFormattedSource, lambda: setattr(source, "type", source_type) ) self.assertEqual(setattr(source, "type", "probes"), None) def test_setting_action(self): kwargs = { "requested": 5, "value": "test", "type": "probes" } source = AtlasChangeSource(**kwargs) for source_action in ["remove", "add"]: self.assertEqual( setattr(source, "action", source_action), None ) self.assertRaises( MalFormattedSource, lambda: setattr(source, "action", "test") ) def test_clean(self): # all ok kwargs = {"requested": 5, "value": "test", "type": "msm", "action": "add"} source = AtlasChangeSource(**kwargs) self.assertEqual(source.clean(), None) # value missing source.value = None self.assertRaises( MalFormattedSource, lambda: source.clean() ) # type missing kwargs = {"requested": 5, "value": "test", "action": "add"} self.assertRaises( MalFormattedSource, lambda: AtlasChangeSource(**kwargs).clean() ) # action missing kwargs = {"requested": 5, "value": "test", "type": "probes"} self.assertRaises( MalFormattedSource, lambda: AtlasChangeSource(**kwargs).clean() ) # requested missing source.value = "test" source.requested = None self.assertRaises( MalFormattedSource, lambda: source.clean() ) def test_build_api_struct(self): kwargs = {"requested": 5, "value": "test", "type": "msm", "action": "add"} source = AtlasChangeSource(**kwargs) self.assertEqual(source.build_api_struct(), kwargs) validate(source.build_api_struct(), probes_change_schema) def test_set_tags(self): # missing action kwargs = { "requested": 5, "value": "test", "type": "msm", "tags": {"include": ["one", "two"], "exclude": ["one", "two"]} } self.assertRaises( MalFormattedSource, lambda: AtlasChangeSource(**kwargs).build_api_struct() ) # action == add kwargs = { "requested": 5, "value": "test", "type": "msm", "action": "add", "tags": {"include": ["one", "two"], "exclude": ["one", "two"]} } source = AtlasChangeSource(**kwargs) self.assertEqual(source.clean(), None) # action == remove kwargs = { "requested": 5, "value": "test", "type": "msm", "action": "remove", "tags": {"include": ["one", "two"], "exclude": ["one", "two"]} } self.assertRaises( MalFormattedSource, lambda: AtlasChangeSource(**kwargs) ) ripe-atlas-cousteau-1.4.2/tox.ini000066400000000000000000000006741325447220000167260ustar00rootroot00000000000000[tox] envlist=py27-pyflakes,py27-pep8,py27-coverage,py27,py34, pypy-5.3.1 [testenv] commands=python setup.py test [] deps=nose [testenv:py27-pep8] commands=pep8 ripe --max-line-length=100 basepython=python2.7 deps=pep8 [testenv:py27-pyflakes] commands=pyflakes ripe basepython=python2.7 deps=pyflakes [testenv:py27-coverage] basepython=python2.7 commands= coverage run --source=ripe setup.py test coverage report -m deps=coverage