././@PaxHeader0000000000000000000000000000003300000000000011451 xustar000000000000000027 mtime=1629405003.428916 monasca-statsd-2.3.0/0000775000175000017500000000000000000000000014460 5ustar00zuulzuul00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1629404972.0 monasca-statsd-2.3.0/.coveragerc0000664000175000017500000000013000000000000016573 0ustar00zuulzuul00000000000000[run] branch = True source = monascastatsd omit = tests/* [report] ignore_errors = True././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1629404972.0 monasca-statsd-2.3.0/.stestr.conf0000664000175000017500000000004700000000000016732 0ustar00zuulzuul00000000000000[DEFAULT] test_path=./tests top_dir=./ ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1629404972.0 monasca-statsd-2.3.0/.zuul.yaml0000664000175000017500000000037400000000000016425 0ustar00zuulzuul00000000000000- project: templates: - check-requirements - openstack-cover-jobs - openstack-lower-constraints-jobs - openstack-python3-xena-jobs check: jobs: - monasca-tempest-python3-influxdb: voting: false ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1629405003.0 monasca-statsd-2.3.0/AUTHORS0000664000175000017500000000313600000000000015533 0ustar00zuulzuul00000000000000Adrian Czarnecki Andreas Jaeger Artur Basiak Cao Xuan Hoang Charles Short Chuck Short Corey Bryant Craig Bryant Denis Poisson Dexter Fryar Dirk Mueller Doug Hellmann Flavio Percoco Ghanshyam Mann Gleb Stepanov Haiwei Xu Hervé Beraud James E. Blair Jeremy Stanley Joe Keen Jui Chandwaskar Kaiyan Sheng Laszlo Hegedus Martin Chacon Piza Masayuki Igawa Michael James Hoppal Nichita Herciu OpenStack Release Bot Sean McGinnis Tomasz Trębski Vu Cong Tuan Witek Bedyk Witold Bedyk ZhongShengping gary-hessler gecong1973 jiasirui melissaml pengyuesheng rajat29 zhangchun zhulingjie ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1629404972.0 monasca-statsd-2.3.0/CONTRIBUTING.rst0000664000175000017500000000116400000000000017123 0ustar00zuulzuul00000000000000The source repository for this project can be found at: https://opendev.org/openstack/monasca-statsd Pull requests submitted through GitHub are not monitored. To start contributing to OpenStack, follow the steps in the contribution guide to set up and use Gerrit: https://docs.openstack.org/contributors/code-and-documentation/quick-start.html Bugs should be filed on Storyboard: https://storyboard.openstack.org/#!/project/872 For more specific information about contributing to this repository, see the Monasca contributor guide: https://docs.openstack.org/monasca-api/latest/contributor/contributing.html ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1629405003.0 monasca-statsd-2.3.0/ChangeLog0000664000175000017500000000734700000000000016245 0ustar00zuulzuul00000000000000CHANGES ======= 2.3.0 ----- * Add Python3 xena unit tests 2.2.0 ----- * Add doc/requirements * bump py37 to py38 in tox.ini * Add Python3 wallaby unit tests * change a better title in README.rst 2.1.0 ----- * Use unittest.mock instead of mock * Remove .testr.conf * Fix and unify cover environment * Add CONTRIBUTING.rst * Fix hacking min version to 3.0.1 * Add py38 package metadata * Add Python3 victoria unit tests * Cleanup py27 support * Update hacking for Python3 2.0.0 ----- * [ussuri][goal] Drop python 2.7 support and testing * Switch to Ussuri jobs * Update the constraints url 1.12.0 ------ * Disable monasca-tempest-java-influxdb job * Add Python 3 Train unit tests * Replace git.openstack.org URLs with opendev.org URLs * OpenDev Migration Patch * Dropping the py35 testing 1.11.0 ------ * add python 3.7 unit test job * add python 3.7 unit test job * Add tempest tests jobs * Update hacking version to latest * Remove setup.py check from pep8 job * fix tox python3 overrides * Use templates for cover and lower-constraints * add python 3.6 unit test job * import zuul job settings from project-config 1.10.1 ------ * Add check for rst syntax * Convert README.md to ReStructuredTest format * Switch to using stestr * fix tox python3 overrides * Remove repository section from README 1.10.0 ------ * Update pep8 check * Update links in README * Clean up tox.ini * add lower-constraints job * Updated from global requirements * Updated from global requirements * Updated from global requirements * Remove PostgreSQL tempest jobs from Zuul * Zuul: Remove project name * Zuul: Remove project name * Updated from global requirements * Updated from global requirements * Updated from global requirements * Updated from global requirements 1.9.0 ----- * Remove -U from pip install * Avoid tox\_install.sh for constraints support * Updated from global requirements * Add .zuul.yaml file 1.8.0 ----- * Updated from global requirements * Updated from global requirements * Updated from global requirements * Updated from global requirements * Fix html\_last\_updated\_fmt for Python3 1.7.0 ----- * Updated from global requirements * Updated from global requirements 1.6.0 ----- * Optimize the link address * Updated from global requirements * Updated from global requirements 1.5.0 ----- * Updated from global requirements * Extend tox for monasca-statsd * Clean up client.py * Clean up connection.py * Clean up counter.py * Extract common update functions * Updated from global requirements * Switch to hacking 0.12.x * Make monasca-statsd PEP8 compatible 1.4.0 ----- * Show team and repo badges on README * Fix setup.cfg * add a summary for the project to fix release announcements 1.3.0 ----- * Clean up the licensing * Add python3 support * Clean imports in code * Allow easy configuration of host/port settings * Delete python bytecode file * Use constraints everywhere * Sync tools/tox\_install.sh * Updated from global requirements * Fixing copyright * Remove reference to removed metric types * Removed H302 * Updated from global requirements * Remove python-statsd from requirements.txt * Removing statsd-generator 1.1.0 ----- * Make imports python 3 compatible * [monasca-statsd] Change tox to use https instead of git * [monasca-statsd] Constraint tox targets with upper-constraints 1.0.4 ----- * Unused function removed * Split line 1.0.3 ----- * Add in HPE Copyrights * Delete python bytecode before every test run 2015.1 ------ * Update .gitreview for new namespace * Add HP Copyright * Added a config file for documentation generation using Markdown and readthedocs.org 1.0.2 ----- * Refactored statsd code to be modular * Fixing issues in generator, unit tests, and documentation 1.0.1 ----- * Adding python client for statsd messages * Added .gitreview ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1629404972.0 monasca-statsd-2.3.0/LICENSE0000664000175000017500000002676500000000000015505 0ustar00zuulzuul00000000000000(C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. --- License for versions prior to monasca-statsd 1.0.0 --- Copyright (c) 2012, Datadog All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Datadog nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DATADOG BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ././@PaxHeader0000000000000000000000000000003300000000000011451 xustar000000000000000027 mtime=1629405003.428916 monasca-statsd-2.3.0/PKG-INFO0000664000175000017500000000756500000000000015572 0ustar00zuulzuul00000000000000Metadata-Version: 1.2 Name: monasca-statsd Version: 2.3.0 Summary: Monasca statsd Python client Home-page: https://opendev.org/openstack/monasca-statsd Maintainer: monasca Maintainer-email: monasca@lists.launchpad.net License: Apache-2 Description: Openstack Monasca Statsd ======================== .. image:: https://governance.openstack.org/tc/badges/monasca-statsd.svg :target: https://governance.openstack.org/tc/reference/tags/index.html A Monasca-Statsd Python Client. =============================== Quick Start Guide ----------------- First install the library with ``pip`` or ``easy_install``: :: # Install in system python ... sudo pip install monasca-statsd # .. or into a virtual env pip install monasca-statsd Then start instrumenting your code: :: # Import the module. import monascastatsd as mstatsd # Create the connection conn = mstatsd.Connection(host='localhost', port=8125) # Create the client with optional dimensions client = mstatsd.Client(connection=conn, dimensions={'env': 'test'}) NOTE: You can also create a client without specifying the connection and it will create the client with the default connection information for the monasca-agent statsd processor daemon which uses host='localhost' and port=8125. client = mstatsd.Client(dimensions={'env': 'test'}) # Increment and decrement a counter. counter = client.get_counter(name='page.views') counter.increment() counter += 3 counter.decrement() counter -= 3 # Record a gauge 50% of the time. gauge = client.get_gauge('gauge', dimensions={'env': 'test'}) gauge.send('metric', 123.4, sample_rate=0.5) # Sample a histogram. histogram = client.get_histogram('histogram', dimensions={'test': 'True'}) histogram.send('metric', 123.4, dimensions={'color': 'red'}) # Time a function call. timer = client.get_timer() @timer.timed('page.render') def render_page(): # Render things ... pass # Time a block of code. timer = client.get_timer() with timer.time('t'): # Do stuff time.sleep(2) # Add dimensions to any metric. histogram = client.get_histogram('my_hist') histogram.send('query.time', 10, dimensions = {'version': '1.0', 'environment': 'dev'}) Feedback -------- To suggest a feature, report a bug, or participate in the general discussion, head over to `StoryBoard`_. License ------- See LICENSE file. Code was originally forked from Datadog’s dogstatsd-python, hence the dual license. .. _StoryBoard: https://storyboard.openstack.org/#!/project/872 Keywords: openstack,monitoring,statsd Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: License :: OSI Approved :: Apache Software License Classifier: Topic :: System :: Monitoring Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: 3 :: Only Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Requires-Python: >=3.6 ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1629404972.0 monasca-statsd-2.3.0/README.rst0000664000175000017500000000446100000000000016154 0ustar00zuulzuul00000000000000Openstack Monasca Statsd ======================== .. image:: https://governance.openstack.org/tc/badges/monasca-statsd.svg :target: https://governance.openstack.org/tc/reference/tags/index.html A Monasca-Statsd Python Client. =============================== Quick Start Guide ----------------- First install the library with ``pip`` or ``easy_install``: :: # Install in system python ... sudo pip install monasca-statsd # .. or into a virtual env pip install monasca-statsd Then start instrumenting your code: :: # Import the module. import monascastatsd as mstatsd # Create the connection conn = mstatsd.Connection(host='localhost', port=8125) # Create the client with optional dimensions client = mstatsd.Client(connection=conn, dimensions={'env': 'test'}) NOTE: You can also create a client without specifying the connection and it will create the client with the default connection information for the monasca-agent statsd processor daemon which uses host='localhost' and port=8125. client = mstatsd.Client(dimensions={'env': 'test'}) # Increment and decrement a counter. counter = client.get_counter(name='page.views') counter.increment() counter += 3 counter.decrement() counter -= 3 # Record a gauge 50% of the time. gauge = client.get_gauge('gauge', dimensions={'env': 'test'}) gauge.send('metric', 123.4, sample_rate=0.5) # Sample a histogram. histogram = client.get_histogram('histogram', dimensions={'test': 'True'}) histogram.send('metric', 123.4, dimensions={'color': 'red'}) # Time a function call. timer = client.get_timer() @timer.timed('page.render') def render_page(): # Render things ... pass # Time a block of code. timer = client.get_timer() with timer.time('t'): # Do stuff time.sleep(2) # Add dimensions to any metric. histogram = client.get_histogram('my_hist') histogram.send('query.time', 10, dimensions = {'version': '1.0', 'environment': 'dev'}) Feedback -------- To suggest a feature, report a bug, or participate in the general discussion, head over to `StoryBoard`_. License ------- See LICENSE file. Code was originally forked from Datadog’s dogstatsd-python, hence the dual license. .. _StoryBoard: https://storyboard.openstack.org/#!/project/872 ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1629404972.0 monasca-statsd-2.3.0/Rakefile0000664000175000017500000000022000000000000016117 0ustar00zuulzuul00000000000000 desc "Run tests" task :test do sh "nosetests" end task :default => :test task :release => :test do sh "python setup.py sdist upload" end ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1629405003.4249153 monasca-statsd-2.3.0/doc/0000775000175000017500000000000000000000000015225 5ustar00zuulzuul00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1629404972.0 monasca-statsd-2.3.0/doc/requirements.txt0000664000175000017500000000015300000000000020510 0ustar00zuulzuul00000000000000sphinx!=1.6.6,!=1.6.7,>=1.6.5 # BSD oslosphinx>=4.7.0 # Apache-2.0 openstackdocstheme>=1.18.1 # Apache-2.0 ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1629405003.4249153 monasca-statsd-2.3.0/doc/source/0000775000175000017500000000000000000000000016525 5ustar00zuulzuul00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1629404972.0 monasca-statsd-2.3.0/doc/source/conf.py0000664000175000017500000002471100000000000020031 0ustar00zuulzuul00000000000000# (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP # Copyright 2017 FUJITSU LIMITED # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. # # Copyright (c) 2012, Datadog # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the Datadog nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL DATADOG BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # -*- coding: utf-8 -*- # # monasca-statsd documentation build configuration file, created by # sphinx-quickstart on Thu Jun 14 19:22:15 2012. # # 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. # 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('.')) import subprocess import warnings # -- 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.todo', 'sphinx.ext.coverage', 'sphinx.ext.viewcode', 'sphinx.ext.graphviz', 'oslosphinx' ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'monasca-statsd' author = u'OpenStack' copyright = u'2014-present, OpenStack Foundatio' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '1.0.0' # The full version, including alpha/beta/rc tags. release = '1.0.0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all documents # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). add_module_names = False # 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 = ['monasca.'] # -- 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'] # 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' git_cmd = ["git", "log", "--pretty=format:'%ad, commit %h'", "--date=local", "-n1"] try: html_last_updated_fmt = subprocess.check_output(git_cmd).decode('utf-8') except Exception: warnings.warn('Cannot get last updated time from git repository. ' 'Not setting "html_last_updated_fmt".') # 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 # Output file base name for HTML help builder. htmlhelp_basename = 'monasca-statsd-pythondoc' # -- Options for LaTeX output ------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # 'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, # documentclass [howto/manual]). latex_documents = [ ('index', 'monasca-statsd-python.tex', u'monasca-statsd-python Documentation', u'OpenStack Foundation', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output ------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'monasca-statsd-python', u'monasca-statsd-python Documentation', [u'OpenStack Foundation'], 1) ] # If true, show URL addresses after external links. # man_show_urls = False # -- Options for Texinfo output ----------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'monasca-statsd-python', u'monasca-statsd-python Documentation', u'Openstack Foundation', 'monasca-statsd-python', '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' ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1629404972.0 monasca-statsd-2.3.0/doc/source/index.rst0000664000175000017500000000122100000000000020362 0ustar00zuulzuul00000000000000Introduction ============ A global :class:`~statsd.MonascaStatsd` instance that is easily shared across an application's modules. Initialize this once in your application's set-up code and then other modules can import and use it without further configuration. >>> from monascastatsd import monascastatsd >>> monascastatsd.connect(host='localhost', port=8125) Source ====== The Monasca-Statsd source is freely available on Github. Check it out `here `_. Get in Touch ============ If you'd like to suggest a feature or report a bug, please add an issue `here `_. ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1629404972.0 monasca-statsd-2.3.0/lower-constraints.txt0000664000175000017500000000136100000000000020717 0ustar00zuulzuul00000000000000alabaster==0.7.10 appdirs==1.4.0 Babel==2.3.4 bandit==1.4.0 coverage==4.0 docutils==0.11 dulwich==0.15.0 extras==1.0.0 fixtures==3.0.0 future==0.16.0 gitdb==0.6.4 GitPython==1.0.1 imagesize==0.7.1 iso8601==0.1.11 Jinja2==2.10 keystoneauth1==3.4.0 linecache2==1.0.0 MarkupSafe==1.0 mccabe==0.6.0 mox3==0.20.0 openstackdocstheme==1.18.1 os-client-config==1.28.0 os-testr==1.0.0 oslosphinx==4.7.0 oslotest==3.2.0 pbr==2.0.0 Pygments==2.2.0 python-mimeparse==1.6.0 python-subunit==1.0.0 pytz==2013.6 PyYAML==3.12 requests==2.14.2 requestsexceptions==1.2.0 six==1.12.0 smmap==0.9.0 snowballstemmer==1.2.1 Sphinx==1.6.5 sphinxcontrib-websupport==1.0.1 stestr==1.0.0 stevedore==1.20.0 testrepository==0.0.18 testtools==2.2.0 traceback2==1.4.0 unittest2==1.1.0 ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1629404972.0 monasca-statsd-2.3.0/mkdocs.yml0000664000175000017500000000012100000000000016455 0ustar00zuulzuul00000000000000site_name: monasca-statsd repo_url: https://github.com/stackforge/monasca-statsd ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1629405003.4249153 monasca-statsd-2.3.0/monasca_statsd.egg-info/0000775000175000017500000000000000000000000021155 5ustar00zuulzuul00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1629405003.0 monasca-statsd-2.3.0/monasca_statsd.egg-info/PKG-INFO0000664000175000017500000000756500000000000022267 0ustar00zuulzuul00000000000000Metadata-Version: 1.2 Name: monasca-statsd Version: 2.3.0 Summary: Monasca statsd Python client Home-page: https://opendev.org/openstack/monasca-statsd Maintainer: monasca Maintainer-email: monasca@lists.launchpad.net License: Apache-2 Description: Openstack Monasca Statsd ======================== .. image:: https://governance.openstack.org/tc/badges/monasca-statsd.svg :target: https://governance.openstack.org/tc/reference/tags/index.html A Monasca-Statsd Python Client. =============================== Quick Start Guide ----------------- First install the library with ``pip`` or ``easy_install``: :: # Install in system python ... sudo pip install monasca-statsd # .. or into a virtual env pip install monasca-statsd Then start instrumenting your code: :: # Import the module. import monascastatsd as mstatsd # Create the connection conn = mstatsd.Connection(host='localhost', port=8125) # Create the client with optional dimensions client = mstatsd.Client(connection=conn, dimensions={'env': 'test'}) NOTE: You can also create a client without specifying the connection and it will create the client with the default connection information for the monasca-agent statsd processor daemon which uses host='localhost' and port=8125. client = mstatsd.Client(dimensions={'env': 'test'}) # Increment and decrement a counter. counter = client.get_counter(name='page.views') counter.increment() counter += 3 counter.decrement() counter -= 3 # Record a gauge 50% of the time. gauge = client.get_gauge('gauge', dimensions={'env': 'test'}) gauge.send('metric', 123.4, sample_rate=0.5) # Sample a histogram. histogram = client.get_histogram('histogram', dimensions={'test': 'True'}) histogram.send('metric', 123.4, dimensions={'color': 'red'}) # Time a function call. timer = client.get_timer() @timer.timed('page.render') def render_page(): # Render things ... pass # Time a block of code. timer = client.get_timer() with timer.time('t'): # Do stuff time.sleep(2) # Add dimensions to any metric. histogram = client.get_histogram('my_hist') histogram.send('query.time', 10, dimensions = {'version': '1.0', 'environment': 'dev'}) Feedback -------- To suggest a feature, report a bug, or participate in the general discussion, head over to `StoryBoard`_. License ------- See LICENSE file. Code was originally forked from Datadog’s dogstatsd-python, hence the dual license. .. _StoryBoard: https://storyboard.openstack.org/#!/project/872 Keywords: openstack,monitoring,statsd Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: License :: OSI Approved :: Apache Software License Classifier: Topic :: System :: Monitoring Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: 3 :: Only Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Requires-Python: >=3.6 ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1629405003.0 monasca-statsd-2.3.0/monasca_statsd.egg-info/SOURCES.txt0000664000175000017500000000146100000000000023043 0ustar00zuulzuul00000000000000.coveragerc .stestr.conf .zuul.yaml AUTHORS CONTRIBUTING.rst ChangeLog LICENSE README.rst Rakefile lower-constraints.txt mkdocs.yml requirements.txt setup.cfg setup.py test-requirements.txt tox.ini doc/requirements.txt doc/source/conf.py doc/source/index.rst monasca_statsd.egg-info/PKG-INFO monasca_statsd.egg-info/SOURCES.txt monasca_statsd.egg-info/dependency_links.txt monasca_statsd.egg-info/not-zip-safe monasca_statsd.egg-info/pbr.json monasca_statsd.egg-info/requires.txt monasca_statsd.egg-info/top_level.txt monascastatsd/__init__.py monascastatsd/client.py monascastatsd/common.py monascastatsd/connection.py monascastatsd/counter.py monascastatsd/gauge.py monascastatsd/metricbase.py monascastatsd/timer.py releasenotes/notes/drop-py-2-7-c9e3758f73d5cf29.yaml tests/__init__.py tests/test_monascastatsd.py././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1629405003.0 monasca-statsd-2.3.0/monasca_statsd.egg-info/dependency_links.txt0000664000175000017500000000000100000000000025223 0ustar00zuulzuul00000000000000 ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1629405003.0 monasca-statsd-2.3.0/monasca_statsd.egg-info/not-zip-safe0000664000175000017500000000000100000000000023403 0ustar00zuulzuul00000000000000 ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1629405003.0 monasca-statsd-2.3.0/monasca_statsd.egg-info/pbr.json0000664000175000017500000000005600000000000022634 0ustar00zuulzuul00000000000000{"git_version": "77fbd15", "is_release": true}././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1629405003.0 monasca-statsd-2.3.0/monasca_statsd.egg-info/requires.txt0000664000175000017500000000001400000000000023550 0ustar00zuulzuul00000000000000six>=1.12.0 ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1629405003.0 monasca-statsd-2.3.0/monasca_statsd.egg-info/top_level.txt0000664000175000017500000000001600000000000023704 0ustar00zuulzuul00000000000000monascastatsd ././@PaxHeader0000000000000000000000000000003300000000000011451 xustar000000000000000027 mtime=1629405003.428916 monasca-statsd-2.3.0/monascastatsd/0000775000175000017500000000000000000000000017324 5ustar00zuulzuul00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1629404972.0 monasca-statsd-2.3.0/monascastatsd/__init__.py0000664000175000017500000000203300000000000021433 0ustar00zuulzuul00000000000000# Copyright 2016 FUJITSU LIMITED # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from monascastatsd import client from monascastatsd import connection from monascastatsd import counter from monascastatsd import gauge from monascastatsd import metricbase from monascastatsd import timer Client = client.Client Connection = connection.Connection Counter = counter.Counter Gauge = gauge.Gauge MetricBase = metricbase.MetricBase Timer = timer.Timer __all__ = [ 'Client', 'Connection', 'Counter', 'Gauge', 'MetricBase', 'Timer' ] ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1629404972.0 monasca-statsd-2.3.0/monascastatsd/client.py0000664000175000017500000001174300000000000021162 0ustar00zuulzuul00000000000000# (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. # # Copyright (c) 2012, Datadog # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the Datadog nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL DATADOG BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Monasca-Statsd is a Python client for Statsd that adds dimensions. """ from monascastatsd import common from monascastatsd.connection import Connection from monascastatsd.counter import Counter from monascastatsd.gauge import Gauge from monascastatsd.timer import Timer class Client(object): def __init__(self, name=None, host='localhost', port=8125, connection=None, max_buffer_size=50, dimensions=None): """Initialize a Client object. >>> monascastatsd = MonascaStatsd() :name: the name for this client. Everything sent by this client will be prefixed by name :param host: the host of the MonascaStatsd server. :param port: the port of the MonascaStatsd server. :param max_buffer_size: Maximum number of metric to buffer before sending to the server if sending metrics in batch """ self._max_buffer_size = max_buffer_size self._set_connection(connection, host, port) self._dimensions = dimensions self._client_name = name def _set_connection(self, connection, host, port): if connection is None: self.connection = Connection(host=host, port=port, max_buffer_size=self._max_buffer_size) else: self.connection = connection def get_counter(self, name, connection=None, dimensions=None): """Gets a Counter object. """ return self._get_statsd_object_by_type(Counter, name, connection, dimensions) def get_gauge(self, name=None, connection=None, dimensions=None): """Gets a Gauge object. """ return self._get_statsd_object_by_type(Gauge, name, connection, dimensions) def get_timer(self, name=None, connection=None, dimensions=None): """Gets a Timer object. """ return self._get_statsd_object_by_type(Timer, name, connection, dimensions) def _get_statsd_object_by_type(self, object_type, name, connection, dimensions): return object_type(name=self._update_metric_name(name), connection=connection or self.connection, dimensions=self._update_dimensions(dimensions)) def _update_metric_name(self, metric_name): """Update the metric name with the client name that was passed in on instantiation. """ return common.update_name(self._client_name, metric_name) def _update_dimensions(self, dimensions): """Update the dimensions list with the default dimensions that were passed in on instantiation. """ return common.update_dimensions(self._dimensions, dimensions) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1629404972.0 monasca-statsd-2.3.0/monascastatsd/common.py0000664000175000017500000000163100000000000021167 0ustar00zuulzuul00000000000000# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. def update_dimensions(dimensions_base=None, dimensions=None): new_dimensions = (dimensions_base or {}).copy() new_dimensions.update(dimensions or {}) return new_dimensions def update_name(name_base=None, postfix=None): if name_base and postfix: return "{}.{}".format(name_base, postfix) else: return name_base or postfix ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1629404972.0 monasca-statsd-2.3.0/monascastatsd/connection.py0000664000175000017500000001311400000000000022035 0ustar00zuulzuul00000000000000# (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP # Copyright 2016 FUJITSU LIMITED # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. # # Copyright (c) 2012, Datadog # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the Datadog nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL DATADOG BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import six import logging import random import socket logging.basicConfig() log = logging.getLogger(__name__) class Connection(object): def __init__(self, host='localhost', port=8125, max_buffer_size=50): """Initialize a Connection object. >>> monascastatsd = MonascaStatsd() :name: the name for this client. Everything sent by this client will be prefixed by name :param host: the host of the MonascaStatsd server. :param port: the port of the MonascaStatsd server. :param max_buffer_size: Maximum number of metric to buffer before sending to the server if sending metrics in batch """ self.max_buffer_size = max_buffer_size self._send = self._send_to_server self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.connect(host, port) self.encoding = 'utf-8' def __enter__(self): self.open_buffer(self.max_buffer_size) return self def __exit__(self, the_type, value, traceback): self.close_buffer() def open_buffer(self, max_buffer_size=50): """Open a buffer to send a batch of metrics in one packet. """ self.max_buffer_size = max_buffer_size self.buffer = [] self._send = self._send_to_buffer def close_buffer(self): """Flush the buffer and switch back to single metric packets. """ self._send = self._send_to_server self._flush_buffer() def connect(self, host, port): """Connect to the monascastatsd server on the given host and port. """ self.socket.connect((host, int(port))) def report(self, metric, metric_type, value, dimensions, sample_rate): """Use this connection to report metrics. """ if sample_rate == 1 or random.random() <= sample_rate: self._send_payload(dimensions, metric, metric_type, sample_rate, value) def _send_payload(self, dimensions, metric, metric_type, sample_rate, value): encoded = self._create_payload(dimensions, metric, metric_type, sample_rate, value) self._send(encoded) def _create_payload(self, dimensions, metric, metric_type, sample_rate, value): payload = [metric, ":", value, "|", metric_type] payload.extend(self._payload_extension_from_sample_rate(sample_rate)) payload.extend(self._payload_extension_from_dimensions(dimensions)) return "".join(six.moves.map(str, payload)) @staticmethod def _payload_extension_from_sample_rate(sample_rate): if sample_rate != 1: return ["|@", sample_rate] else: return [] @staticmethod def _payload_extension_from_dimensions(dimensions): if dimensions: return ["|#", dimensions] else: return [] def _send_to_server(self, packet): try: self.socket.send(packet.encode(self.encoding)) except socket.error: log.exception("Error submitting metric") def _send_to_buffer(self, packet): self.buffer.append(packet) if len(self.buffer) >= self.max_buffer_size: self._flush_buffer() def _flush_buffer(self): self._send_to_server("\n".join(self.buffer)) self.buffer = [] ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1629404972.0 monasca-statsd-2.3.0/monascastatsd/counter.py0000664000175000017500000000754700000000000021372 0ustar00zuulzuul00000000000000# (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. # # Copyright (c) 2012, Datadog # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the Datadog nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL DATADOG BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from monascastatsd import metricbase class Counter(metricbase.MetricBase): def __init__(self, name, connection, dimensions=None): super(self.__class__, self).__init__(name=name, connection=connection, dimensions=dimensions) def increment(self, value=1, dimensions=None, sample_rate=1): """Increment a counter, optionally setting a value, dimensions and a sample rate. >>> monascastatsd.increment() >>> monascastatsd.increment(12) """ self._report_change(dimensions, sample_rate, value) def decrement(self, value=1, dimensions=None, sample_rate=1): """Decrement a counter, optionally setting a value, dimensions and a sample rate. >>> monascastatsd.decrement() >>> monascastatsd.decrement(2) """ self._report_change(dimensions, sample_rate, -value) def _report_change(self, dimensions, sample_rate, value): self._connection.report(metric=self._name, metric_type='c', value=value, dimensions=self.update_dimensions(dimensions), sample_rate=sample_rate) def __add__(self, value): """Increment the counter with `value` :keyword value: The value to add to the counter :type value: int """ self.increment(value=value) return self def __sub__(self, value): """Decrement the counter with `value` :keyword value: The value to remove from the counter :type value: int """ self.decrement(value=value) return self ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1629404972.0 monasca-statsd-2.3.0/monascastatsd/gauge.py0000664000175000017500000000611300000000000020767 0ustar00zuulzuul00000000000000# (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. # # Copyright (c) 2012, Datadog # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the Datadog nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL DATADOG BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from monascastatsd import metricbase class Gauge(metricbase.MetricBase): def __init__(self, connection, name=None, dimensions=None): super(self.__class__, self).__init__(name=name, connection=connection, dimensions=dimensions) def send(self, name, value, dimensions=None, sample_rate=1): """Record the value of a gauge, optionally setting a list of dimensions and a sample rate. >>> monascastatsd.gauge('users.online', 123) >>> monascastatsd.gauge('active.connections', 1001, >>> dimensions={"protocol": "http"}) """ self._connection.report(metric=self.update_name(name), metric_type='g', value=value, dimensions=self.update_dimensions(dimensions), sample_rate=sample_rate) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1629404972.0 monasca-statsd-2.3.0/monascastatsd/metricbase.py0000664000175000017500000000547100000000000022023 0ustar00zuulzuul00000000000000# (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. # # Copyright (c) 2012, Datadog # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the Datadog nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL DATADOG BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from monascastatsd import common class MetricBase(object): """Base class for all metric types. """ def __init__(self, name, connection, dimensions): self._name = name self._connection = connection self._dimensions = dimensions def update_dimensions(self, dimensions): """Update the dimensions list with the default dimensions that were passed in on instantiation. """ return common.update_dimensions(self._dimensions, dimensions) def update_name(self, name): """Update the metric name with the metric base name that was passed in on instantiation. """ return common.update_name(self._name, name) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1629404972.0 monasca-statsd-2.3.0/monascastatsd/timer.py0000664000175000017500000001122600000000000021020 0ustar00zuulzuul00000000000000# (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. # # Copyright (c) 2012, Datadog # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the Datadog nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL DATADOG BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import contextlib import functools import time from monascastatsd import metricbase class Timer(metricbase.MetricBase): def __init__(self, connection, name=None, dimensions=None): super(self.__class__, self).__init__(name=name, connection=connection, dimensions=dimensions) def timing(self, name, value, dimensions=None, sample_rate=1): """Record a timing, optionally setting dimensions and a sample rate. >>> monascastatsd.timing("query.response.time", 1234) """ self._connection.report(metric=self.update_name(name), metric_type='g', value=value, dimensions=self.update_dimensions(dimensions), sample_rate=sample_rate) def timed(self, name, dimensions=None, sample_rate=1): """A decorator that will measure the distribution of a function's run time. Optionally specify a list of tag or a sample rate. :: @monascastatsd.timed('user.query.time', sample_rate=0.5) def get_user(user_id): # Do what you need to ... pass # Is equivalent to ... start = time.time() try: get_user(user_id) finally: monascastatsd.timing('user.query.time', time.time() - start) """ def wrapper(func): @functools.wraps(func) def wrapped(*args, **kwargs): start = time.time() result = func(*args, **kwargs) self.timing(name, time.time() - start, dimensions=dimensions, sample_rate=sample_rate) return result wrapped.__name__ = func.__name__ wrapped.__doc__ = func.__doc__ wrapped.__dict__.update(func.__dict__) return wrapped return wrapper @contextlib.contextmanager def time(self, name, dimensions=None, sample_rate=1): """Time a block of code, optionally setting dimensions and a sample rate. try: with monascastatsd.time("query.response.time"): Do something... except Exception: Log something... """ start_time = time.time() yield end_time = time.time() self.timing(name, end_time - start_time, dimensions, sample_rate) ././@PaxHeader0000000000000000000000000000003300000000000011451 xustar000000000000000027 mtime=1629405003.420915 monasca-statsd-2.3.0/releasenotes/0000775000175000017500000000000000000000000017151 5ustar00zuulzuul00000000000000././@PaxHeader0000000000000000000000000000003300000000000011451 xustar000000000000000027 mtime=1629405003.428916 monasca-statsd-2.3.0/releasenotes/notes/0000775000175000017500000000000000000000000020301 5ustar00zuulzuul00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1629404972.0 monasca-statsd-2.3.0/releasenotes/notes/drop-py-2-7-c9e3758f73d5cf29.yaml0000664000175000017500000000033200000000000025322 0ustar00zuulzuul00000000000000--- upgrade: - | Python 2.7 support has been dropped. Last release of monasca-statsd to support python 2.7 is OpenStack Train. The minimum version of Python now supported by monasca-statsd is Python 3.6. ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1629404972.0 monasca-statsd-2.3.0/requirements.txt0000664000175000017500000000034400000000000017745 0ustar00zuulzuul00000000000000# The order of packages is significant, because pip processes them in the order # of appearance. Changing the order has an impact on the overall integration # process, which may cause wedges in the gate later. six>=1.12.0 # MIT ././@PaxHeader0000000000000000000000000000003300000000000011451 xustar000000000000000027 mtime=1629405003.428916 monasca-statsd-2.3.0/setup.cfg0000664000175000017500000000176300000000000016310 0ustar00zuulzuul00000000000000[metadata] name = monasca-statsd maintainer = monasca maintainer_email = monasca@lists.launchpad.net description-file = README.rst summary = Monasca statsd Python client home-page = https://opendev.org/openstack/monasca-statsd keywords = openstack monitoring statsd license = Apache-2 include_package_data = True test_suite = nose.collector python-requires = >=3.6 classifier = Development Status :: 5 - Production/Stable License :: OSI Approved :: Apache Software License Topic :: System :: Monitoring Programming Language :: Python Programming Language :: Python :: Implementation :: CPython Programming Language :: Python :: 3 :: Only Programming Language :: Python :: 3 Programming Language :: Python :: 3.6 Programming Language :: Python :: 3.7 Programming Language :: Python :: 3.8 [files] packages = monascastatsd [pbr] autodoc_index_modules = True [egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 [build_sphinx] all_files = 1 build-dir = doc/build source-dir = doc/source ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1629404972.0 monasca-statsd-2.3.0/setup.py0000664000175000017500000000127100000000000016173 0ustar00zuulzuul00000000000000# Copyright (c) 2013 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import setuptools setuptools.setup( setup_requires=['pbr>=2.0.0'], pbr=True) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1629404972.0 monasca-statsd-2.3.0/test-requirements.txt0000664000175000017500000000062100000000000020720 0ustar00zuulzuul00000000000000# The order of packages is significant, because pip processes them in the order # of appearance. Changing the order has an impact on the overall integration # process, which may cause wedges in the gate later. hacking>=3.0.1,<3.1.0 # Apache-2.0 bandit>=1.1.0 # Apache-2.0 coverage!=4.4,>=4.0 # Apache-2.0 oslotest>=3.2.0 # Apache-2.0 stestr>=1.0.0 # Apache-2.0 testrepository>=0.0.18 # Apache-2.0/BSD ././@PaxHeader0000000000000000000000000000003300000000000011451 xustar000000000000000027 mtime=1629405003.428916 monasca-statsd-2.3.0/tests/0000775000175000017500000000000000000000000015622 5ustar00zuulzuul00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1629404972.0 monasca-statsd-2.3.0/tests/__init__.py0000664000175000017500000000000000000000000017721 0ustar00zuulzuul00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1629404972.0 monasca-statsd-2.3.0/tests/test_monascastatsd.py0000664000175000017500000002662400000000000022111 0ustar00zuulzuul00000000000000# (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. # # Copyright (c) 2012, Datadog # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the Datadog nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL DATADOG BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # -*- coding: utf-8 -*- """Tests for monascastatsd.py.""" import collections import socket import time import unittest import monascastatsd as mstatsd from unittest import mock import six from six.moves import range class FakeSocket(object): """A fake socket for testing.""" def __init__(self): self.payloads = collections.deque() def send(self, payload): self.payloads.append(payload) def recv(self): try: return self.payloads.popleft() except IndexError: return None def __repr__(self): return str(self.payloads) class BrokenSocket(FakeSocket): def send(self, payload): raise socket.error("Socket error") class TestMonascaStatsd(unittest.TestCase): def setUp(self): conn = mstatsd.Connection() conn.socket = FakeSocket() self.client = mstatsd.Client(connection=conn, dimensions={'env': 'test'}) def recv(self, metric_obj): return metric_obj._connection.socket.recv() @mock.patch('monascastatsd.client.Connection') def test_client_set_host_port(self, connection_mock): mstatsd.Client(host='foo.bar', port=5213) connection_mock.assert_called_once_with(host='foo.bar', port=5213, max_buffer_size=50) @mock.patch('monascastatsd.client.Connection') def test_client_default_host_port(self, connection_mock): mstatsd.Client() connection_mock.assert_called_once_with(host='localhost', port=8125, max_buffer_size=50) def test_counter(self): counter = self.client.get_counter(name='page.views') counter.increment() self.assertEqual(six.b("page.views:1|c|#{'env': 'test'}"), self.recv(counter)) counter += 1 self.assertEqual(six.b("page.views:1|c|#{'env': 'test'}"), self.recv(counter)) counter.increment(11) self.assertEqual(six.b("page.views:11|c|#{'env': 'test'}"), self.recv(counter)) counter += 11 self.assertEqual(six.b("page.views:11|c|#{'env': 'test'}"), self.recv(counter)) counter.decrement() self.assertEqual(six.b("page.views:-1|c|#{'env': 'test'}"), self.recv(counter)) counter -= 1 self.assertEqual(six.b("page.views:-1|c|#{'env': 'test'}"), self.recv(counter)) counter.decrement(12) self.assertEqual(six.b("page.views:-12|c|#{'env': 'test'}"), self.recv(counter)) counter -= 12 self.assertEqual(six.b("page.views:-12|c|#{'env': 'test'}"), self.recv(counter)) def test_counter_with_dimensions(self): counter = self.client.get_counter('counter_with_dims', dimensions={'date': '10/24', 'time': '23:00'}) counter.increment(dimensions={'country': 'canada', 'color': 'red'}) result = self.recv(counter) if isinstance(result, bytes): result = result.decode('utf-8') self.assertRegexpMatches(result, "counter_with_dims:1|c|#{") self.assertRegexpMatches(result, "'country': 'canada'") self.assertRegexpMatches(result, "'date': '10/24'") self.assertRegexpMatches(result, "'color': 'red'") self.assertRegexpMatches(result, "'env': 'test'") self.assertRegexpMatches(result, "'time': '23:00'") counter += 1 result = self.recv(counter) if isinstance(result, bytes): result = result.decode('utf-8') self.assertRegexpMatches(result, "counter_with_dims:1|c|#{") self.assertRegexpMatches(result, "'date': '10/24'") self.assertRegexpMatches(result, "'env': 'test'") self.assertRegexpMatches(result, "'time': '23:00'") def test_gauge(self): gauge = self.client.get_gauge('gauge') gauge.send('metric', 123.4) result = self.recv(gauge) if isinstance(result, bytes): result = result.decode('utf-8') assert result == "gauge.metric:123.4|g|#{'env': 'test'}" def test_gauge_with_dimensions(self): gauge = self.client.get_gauge('gauge') gauge.send('gt', 123.4, dimensions={'country': 'china', 'age': 45, 'color': 'blue'}) result = self.recv(gauge) if isinstance(result, bytes): result = result.decode('utf-8') self.assertRegexpMatches(result, "gauge.gt:123.4|g|#{") self.assertRegexpMatches(result, "'country': 'china'") self.assertRegexpMatches(result, "'age': 45") self.assertRegexpMatches(result, "'color': 'blue'") self.assertRegexpMatches(result, "'env': 'test'") def test_sample_rate(self): counter = self.client.get_counter('sampled_counter') counter.increment(sample_rate=0) assert not self.recv(counter) for _ in range(10000): counter.increment(sample_rate=0.3) self.assert_almost_equal(3000, len(self.client.connection.socket.payloads), 150) self.assertEqual(six.b("sampled_counter:1|c|@0.3|#{'env': 'test'}"), self.recv(counter)) def test_samples_with_dimensions(self): gauge = self.client.get_gauge() for _ in range(100): gauge.send('gst', 23, dimensions={'status': 'sampled'}, sample_rate=0.9) def test_timing(self): timer = self.client.get_timer() timer.timing('t', 123) self.assertEqual(six.b("t:123|g|#{'env': 'test'}"), self.recv(timer)) def test_time(self): timer = self.client.get_timer() with timer.time('t'): time.sleep(2) packet = self.recv(timer) if isinstance(packet, bytes): packet = packet.decode("utf-8") name_value, type_, dimensions = packet.split('|') name, value = name_value.split(':') self.assertEqual('g', type_) self.assertEqual('t', name) self.assert_almost_equal(2.0, float(value), 0.1) self.assertEqual("{'env': 'test'}", dimensions.lstrip('#')) def test_timed(self): timer = self.client.get_timer() @timer.timed('timed.test') def func(a, b, c=1, d=1): """docstring.""" time.sleep(0.5) return (a, b, c, d) self.assertEqual('func', func.__name__) self.assertEqual('docstring.', func.__doc__) result = func(1, 2, d=3) # Assert it handles args and kwargs correctly. self.assertEqual(result, (1, 2, 1, 3)) packet = self.recv(timer) if isinstance(packet, bytes): packet = packet.decode("utf-8") name_value, type_, dimensions = packet.split('|') name, value = name_value.split(':') self.assertEqual('g', type_) self.assertEqual('timed.test', name) self.assert_almost_equal(0.5, float(value), 0.1) self.assertEqual("{'env': 'test'}", dimensions.lstrip('#')) def test_socket_error(self): self.client.connection.socket = BrokenSocket() self.client.get_gauge().send('no error', 1) assert True, 'success' self.client.connection.socket = FakeSocket() def test_batched(self): self.client.connection.open_buffer() gauge = self.client.get_gauge('site') gauge.send('views', 123) timer = self.client.get_timer('site') timer.timing('timer', 123) self.client.connection.close_buffer() self.assertEqual(six.b("site.views:123|g|#{'env': 'test'}\n" "site.timer:123|g|#{'env': 'test'}"), self.recv(gauge)) def test_context_manager(self): fake_socket = FakeSocket() with mstatsd.Connection() as conn: conn.socket = fake_socket client = mstatsd.Client(name='ContextTester', connection=conn) client.get_gauge('page').send('views', 123) client.get_timer('page').timing('timer', 12) self.assertEqual(six.b('ContextTester.page.views:123|g\nContextTester.page.timer:12|g'), fake_socket.recv()) def test_batched_buffer_autoflush(self): fake_socket = FakeSocket() with mstatsd.Connection() as conn: conn.socket = fake_socket client = mstatsd.Client(name='BufferedTester', connection=conn) counter = client.get_counter('mycounter') for _ in range(51): counter.increment() self.assertEqual(six.b('\n'.join(['BufferedTester.mycounter:1|c' for _ in range(50)])), fake_socket.recv()) self.assertEqual(six.b('BufferedTester.mycounter:1|c'), fake_socket.recv()) @staticmethod def assert_almost_equal(a, b, delta): assert 0 <= abs(a - b) <= delta, "%s - %s not within %s" % (a, b, delta) if __name__ == '__main__': unittest.main() ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1629404972.0 monasca-statsd-2.3.0/tox.ini0000664000175000017500000000320600000000000015774 0ustar00zuulzuul00000000000000[tox] envlist = py38,pep8,cover minversion = 2.5 skipsdist = True [testenv] basepython = python3 passenv = http_proxy HTTP_PROXY https_proxy HTTPS_PROXY no_proxy NO_PROXY usedevelop = True install_command = pip install {opts} {packages} deps = -c{env:UPPER_CONSTRAINTS_FILE:https://releases.openstack.org/constraints/upper/master} -r{toxinidir}/requirements.txt -r{toxinidir}/test-requirements.txt whitelist_externals = bash find rm commands = find . -type f -name "*.py[c|o]" -delete stestr run {posargs} [testenv:cover] description = Calculates code coverage setenv = PYTHON=coverage run --source monascastatsd --parallel-mode commands = stestr run {posargs} coverage combine coverage html -d cover coverage xml -o cover/coverage.xml [testenv:debug] commands = oslo_debug_helper -t {toxinidir}/tests {posargs} [testenv:docs] deps = -c{env:TOX_CONSTRAINTS_FILE:https://releases.openstack.org/constraints/upper/master} -r{toxinidir}/doc/requirements.txt commands = rm -rf doc/build python setup.py build_sphinx [testenv:bandit] commands = bandit -r monascastatsd -s B311 -n5 -x monascastatsd/tests [testenv:flake8] commands = flake8 monascastatsd [testenv:pep8] commands = {[testenv:flake8]commands} {[testenv:bandit]commands} [testenv:venv] commands = {posargs} [flake8] show-source = True exclude=.venv,.git,.tox,dist,*egg,build,docs,cover max-line-length = 100 [testenv:lower-constraints] deps = -c{toxinidir}/lower-constraints.txt -r{toxinidir}/test-requirements.txt -r{toxinidir}/requirements.txt