pax_global_header00006660000000000000000000000064134325100250014505gustar00rootroot0000000000000052 comment=0156d20a4d25bb93fd62732749dcb8cabcf8dd2f monasca-statsd-1.11.0/000077500000000000000000000000001343251002500145065ustar00rootroot00000000000000monasca-statsd-1.11.0/.coveragerc000066400000000000000000000001301343251002500166210ustar00rootroot00000000000000[run] branch = True source = monascastatsd omit = tests/* [report] ignore_errors = Truemonasca-statsd-1.11.0/.gitignore000066400000000000000000000002111343251002500164700ustar00rootroot00000000000000.pydevproject .project .settings *.pyc build dist *.egg-info .tox AUTHORS ChangeLog .coverage cover/ .testrepository/ doc/build/ .stestr monasca-statsd-1.11.0/.gitreview000066400000000000000000000001231343251002500165100ustar00rootroot00000000000000[gerrit] host=review.openstack.org port=29418 project=openstack/monasca-statsd.git monasca-statsd-1.11.0/.stestr.conf000066400000000000000000000000471343251002500167600ustar00rootroot00000000000000[DEFAULT] test_path=./tests top_dir=./ monasca-statsd-1.11.0/.testr.conf000066400000000000000000000005551343251002500166010ustar00rootroot00000000000000[DEFAULT] test_command=OS_STDOUT_CAPTURE=${OS_STDOUT_CAPTURE:-1} \ OS_STDERR_CAPTURE=${OS_STDERR_CAPTURE:-1} \ OS_TEST_TIMEOUT=${OS_TEST_TIMEOUT:-160} \ ${PYTHON:-python} -m subunit.run discover -t ./ $OS_TEST_PATH $LISTOPT $IDOPTION test_id_option=--load-list $IDFILE test_list_option=--list group_regex=tests(?:\.|_)([^_]+)monasca-statsd-1.11.0/.zuul.yaml000066400000000000000000000007371343251002500164560ustar00rootroot00000000000000- project: templates: - check-requirements - openstack-cover-jobs - openstack-lower-constraints-jobs - openstack-python-jobs - openstack-python35-jobs - openstack-python36-jobs - openstack-python37-jobs check: jobs: - monasca-tempest-python2-influxdb: voting: false - monasca-tempest-python3-influxdb: voting: false - monasca-tempest-java-influxdb: voting: false monasca-statsd-1.11.0/LICENSE000066400000000000000000000267651343251002500155330ustar00rootroot00000000000000(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. monasca-statsd-1.11.0/README.rst000066400000000000000000000044611343251002500162020ustar00rootroot00000000000000Team and repository tags ======================== .. 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 monasca-statsd-1.11.0/Rakefile000066400000000000000000000002201343251002500161450ustar00rootroot00000000000000 desc "Run tests" task :test do sh "nosetests" end task :default => :test task :release => :test do sh "python setup.py sdist upload" end monasca-statsd-1.11.0/doc/000077500000000000000000000000001343251002500152535ustar00rootroot00000000000000monasca-statsd-1.11.0/doc/source/000077500000000000000000000000001343251002500165535ustar00rootroot00000000000000monasca-statsd-1.11.0/doc/source/conf.py000066400000000000000000000247011343251002500200560ustar00rootroot00000000000000# (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' monasca-statsd-1.11.0/doc/source/index.rst000066400000000000000000000012211343251002500204100ustar00rootroot00000000000000Introduction ============ 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 `_. monasca-statsd-1.11.0/lower-constraints.txt000066400000000000000000000014671343251002500207540ustar00rootroot00000000000000alabaster==0.7.10 appdirs==1.3.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 flake8==2.5.5 future==0.16.0 gitdb==0.6.4 GitPython==1.0.1 hacking==0.12.0 imagesize==0.7.1 iso8601==0.1.11 Jinja2==2.10 keystoneauth1==3.4.0 linecache2==1.0.0 MarkupSafe==1.0 mccabe==0.2.1 mock==2.0.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 pep8==1.5.7 pyflakes==0.8.1 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.10.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 monasca-statsd-1.11.0/mkdocs.yml000066400000000000000000000001211343251002500165030ustar00rootroot00000000000000site_name: monasca-statsd repo_url: https://github.com/stackforge/monasca-statsd monasca-statsd-1.11.0/monascastatsd/000077500000000000000000000000001343251002500173525ustar00rootroot00000000000000monasca-statsd-1.11.0/monascastatsd/__init__.py000066400000000000000000000020331343251002500214610ustar00rootroot00000000000000# 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' ] monasca-statsd-1.11.0/monascastatsd/client.py000066400000000000000000000117431343251002500212100ustar00rootroot00000000000000# (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) monasca-statsd-1.11.0/monascastatsd/common.py000066400000000000000000000016311343251002500212150ustar00rootroot00000000000000# 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 monasca-statsd-1.11.0/monascastatsd/connection.py000066400000000000000000000131141343251002500220630ustar00rootroot00000000000000# (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 = [] monasca-statsd-1.11.0/monascastatsd/counter.py000066400000000000000000000075471343251002500214200ustar00rootroot00000000000000# (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 monasca-statsd-1.11.0/monascastatsd/gauge.py000066400000000000000000000061131343251002500210150ustar00rootroot00000000000000# (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) monasca-statsd-1.11.0/monascastatsd/metricbase.py000066400000000000000000000054711343251002500220510ustar00rootroot00000000000000# (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) monasca-statsd-1.11.0/monascastatsd/timer.py000066400000000000000000000112261343251002500210460ustar00rootroot00000000000000# (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) monasca-statsd-1.11.0/requirements.txt000066400000000000000000000003441343251002500177730ustar00rootroot00000000000000# 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.10.0 # MIT monasca-statsd-1.11.0/setup.cfg000066400000000000000000000016041343251002500163300ustar00rootroot00000000000000[metadata] name = monasca-statsd maintainer = monasca maintainer_email = monasca@lists.launchpad.net description-file = README.rst summary = Monasca statsd Python client home-page = https://github.com/openstack/monasca-statsd keywords= openstack monitoring statsd license = Apache-2 include_package_data = True test_suite = nose.collector classifier = Development Status :: 5 - Production/Stable License :: OSI Approved :: Apache Software License Topic :: System :: Monitoring Programming Language :: Python Programming Language :: Python :: 2.7 Programming Language :: Python :: 3.5 [files] packages = monascastatsd [global] setup-hooks = pbr.hooks.setup_hook [pbr] autodoc_index_modules = True [wheel] universal = 1 [egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 [build_sphinx] all_files = 1 build-dir = doc/build source-dir = doc/source monasca-statsd-1.11.0/setup.py000066400000000000000000000020061343251002500162160ustar00rootroot00000000000000# 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. # THIS FILE IS MANAGED BY THE GLOBAL REQUIREMENTS REPO - DO NOT EDIT import setuptools # In python < 2.7.4, a lazy loading of package `pbr` will break # setuptools if some other modules registered functions in `atexit`. # solution from: http://bugs.python.org/issue15881#msg170215 try: import multiprocessing # noqa except ImportError: pass setuptools.setup( setup_requires=['pbr>=2.0.0'], pbr=True) monasca-statsd-1.11.0/test-requirements.txt000066400000000000000000000010161343251002500207450ustar00rootroot00000000000000# 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>=1.1.0,<1.2.0 # Apache-2.0 bandit>=1.1.0 # Apache-2.0 coverage!=4.4,>=4.0 # Apache-2.0 mock>=2.0.0 # BSD sphinx!=1.6.6,!=1.6.7,>=1.6.5 # BSD oslosphinx>=4.7.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 openstackdocstheme>=1.18.1 # Apache-2.0 monasca-statsd-1.11.0/tests/000077500000000000000000000000001343251002500156505ustar00rootroot00000000000000monasca-statsd-1.11.0/tests/__init__.py000066400000000000000000000000001343251002500177470ustar00rootroot00000000000000monasca-statsd-1.11.0/tests/test_monascastatsd.py000066400000000000000000000265431343251002500221370ustar00rootroot00000000000000# (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 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'}\nsite.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() monasca-statsd-1.11.0/tox.ini000066400000000000000000000031401343251002500160170ustar00rootroot00000000000000[tox] envlist = py{27,35},pep8,cover minversion = 2.5 skipsdist = True [testenv] 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://git.openstack.org/cgit/openstack/requirements/plain/upper-constraints.txt} -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] basepython = python3 commands = coverage erase python setup.py test --coverage --testr-args='{posargs}' --coverage-package-name=monascastatsd coverage report [testenv:debug] basepython = python3 commands = oslo_debug_helper -t {toxinidir}/tests {posargs} [testenv:docs] basepython = python3 commands = rm -rf doc/build python setup.py build_sphinx [testenv:bandit] basepython = python3 commands = bandit -r monascastatsd -s B311 -n5 -x monascastatsd/tests [testenv:flake8] basepython = python3 commands = flake8 monascastatsd [testenv:pep8] basepython = python3 commands = {[testenv:flake8]commands} {[testenv:bandit]commands} [testenv:venv] basepython = python3 commands = {posargs} [flake8] show-source = True exclude=.venv,.git,.tox,dist,*egg,build,docs,cover max-line-length = 100 [testenv:lower-constraints] basepython = python3 deps = -c{toxinidir}/lower-constraints.txt -r{toxinidir}/test-requirements.txt -r{toxinidir}/requirements.txt