monasca-statsd-1.9.0/0000775000175100017510000000000013217007770014472 5ustar zuulzuul00000000000000monasca-statsd-1.9.0/.zuul.yaml0000666000175100017510000000052213217007600016424 0ustar zuulzuul00000000000000- project: name: openstack/monasca-statsd check: jobs: - monasca-tempest-python-mysql: voting: false - monasca-tempest-python-postgresql: voting: false - monasca-tempest-java-mysql: voting: false - monasca-tempest-java-postgresql: voting: falsemonasca-statsd-1.9.0/.coveragerc0000666000175100017510000000013013217007600016577 0ustar zuulzuul00000000000000[run] branch = True source = monascastatsd omit = tests/* [report] ignore_errors = Truemonasca-statsd-1.9.0/Rakefile0000666000175100017510000000022013217007600016123 0ustar zuulzuul00000000000000 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.9.0/PKG-INFO0000664000175100017510000000723513217007770015576 0ustar zuulzuul00000000000000Metadata-Version: 1.1 Name: monasca-statsd Version: 1.9.0 Summary: Monasca statsd Python client Home-page: https://github.com/openstack/monasca-statsd Author: monasca Author-email: monasca@lists.launchpad.net License: Apache-2 Description-Content-Type: UNKNOWN Description: Team and repository tags ======================== [![Team and repository tags](https://governance.openstack.org/badges/monasca-statsd.svg)](https://governance.openstack.org/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'}) ``` Repository ------------- The monasca-statsd code is located here: [here](https://github.com/stackforge/monasca-statsd). Feedback -------- To suggest a feature, report a bug, or general discussion, head over [here](https://bugs.launchpad.net/monasca). License ------- See LICENSE file Code was originally forked from Datadog's dogstatsd-python, hence the dual license. 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 :: 2.7 Classifier: Programming Language :: Python :: 3.5 monasca-statsd-1.9.0/setup.py0000666000175100017510000000200613217007600016174 0ustar zuulzuul00000000000000# 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.9.0/LICENSE0000666000175100017510000002676513217007600015511 0ustar zuulzuul00000000000000(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.9.0/test-requirements.txt0000666000175100017510000000101213217007600020717 0ustar zuulzuul00000000000000# 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!=0.13.0,<0.14,>=0.12.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.2 # BSD oslosphinx>=4.7.0 # Apache-2.0 oslotest>=1.10.0 # Apache-2.0 os-testr>=1.0.0 # Apache-2.0 testrepository>=0.0.18 # Apache-2.0/BSD openstackdocstheme>=1.17.0 # Apache-2.0 monasca-statsd-1.9.0/.testr.conf0000666000175100017510000000055513217007600016557 0ustar zuulzuul00000000000000[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.9.0/doc/0000775000175100017510000000000013217007770015237 5ustar zuulzuul00000000000000monasca-statsd-1.9.0/doc/source/0000775000175100017510000000000013217007770016537 5ustar zuulzuul00000000000000monasca-statsd-1.9.0/doc/source/conf.py0000666000175100017510000002470113217007600020034 0ustar zuulzuul00000000000000# (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.9.0/doc/source/index.rst0000666000175100017510000000122113217007600020366 0ustar zuulzuul00000000000000Introduction ============ 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.9.0/setup.cfg0000666000175100017510000000155113217007770016317 0ustar zuulzuul00000000000000[metadata] name = monasca-statsd maintainer = monasca maintainer_email = monasca@lists.launchpad.net description-file = README.md 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.9.0/requirements.txt0000666000175100017510000000034413217007600017751 0ustar zuulzuul00000000000000# 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.9.0/tests/0000775000175100017510000000000013217007770015634 5ustar zuulzuul00000000000000monasca-statsd-1.9.0/tests/__init__.py0000666000175100017510000000000013217007600017725 0ustar zuulzuul00000000000000monasca-statsd-1.9.0/tests/test_monascastatsd.py0000666000175100017510000002654313217007600022115 0ustar zuulzuul00000000000000# (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.9.0/README.md0000666000175100017510000000444113217007600015746 0ustar zuulzuul00000000000000Team and repository tags ======================== [![Team and repository tags](https://governance.openstack.org/badges/monasca-statsd.svg)](https://governance.openstack.org/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'}) ``` Repository ------------- The monasca-statsd code is located here: [here](https://github.com/stackforge/monasca-statsd). Feedback -------- To suggest a feature, report a bug, or general discussion, head over [here](https://bugs.launchpad.net/monasca). License ------- See LICENSE file Code was originally forked from Datadog's dogstatsd-python, hence the dual license. monasca-statsd-1.9.0/mkdocs.yml0000666000175100017510000000012113217007600016461 0ustar zuulzuul00000000000000site_name: monasca-statsd repo_url: https://github.com/stackforge/monasca-statsd monasca-statsd-1.9.0/ChangeLog0000664000175100017510000000402513217007767016253 0ustar zuulzuul00000000000000CHANGES ======= 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 monasca-statsd-1.9.0/AUTHORS0000664000175100017510000000157613217007767015561 0ustar zuulzuul00000000000000Adrian Czarnecki Andreas Jaeger Artur Basiak Cao Xuan Hoang Chuck Short Craig Bryant Dexter Fryar Dirk Mueller Doug Hellmann Flavio Percoco Gleb Stepanov Haiwei Xu Jeremy Stanley Joe Keen Kaiyan Sheng Laszlo Hegedus Michael James Hoppal Nichita Herciu Tomasz Trębski Vu Cong Tuan gary-hessler gecong1973 rajat29 monasca-statsd-1.9.0/monasca_statsd.egg-info/0000775000175100017510000000000013217007770021167 5ustar zuulzuul00000000000000monasca-statsd-1.9.0/monasca_statsd.egg-info/PKG-INFO0000664000175100017510000000723513217007767022301 0ustar zuulzuul00000000000000Metadata-Version: 1.1 Name: monasca-statsd Version: 1.9.0 Summary: Monasca statsd Python client Home-page: https://github.com/openstack/monasca-statsd Author: monasca Author-email: monasca@lists.launchpad.net License: Apache-2 Description-Content-Type: UNKNOWN Description: Team and repository tags ======================== [![Team and repository tags](https://governance.openstack.org/badges/monasca-statsd.svg)](https://governance.openstack.org/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'}) ``` Repository ------------- The monasca-statsd code is located here: [here](https://github.com/stackforge/monasca-statsd). Feedback -------- To suggest a feature, report a bug, or general discussion, head over [here](https://bugs.launchpad.net/monasca). License ------- See LICENSE file Code was originally forked from Datadog's dogstatsd-python, hence the dual license. 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 :: 2.7 Classifier: Programming Language :: Python :: 3.5 monasca-statsd-1.9.0/monasca_statsd.egg-info/top_level.txt0000664000175100017510000000001613217007767023724 0ustar zuulzuul00000000000000monascastatsd monasca-statsd-1.9.0/monasca_statsd.egg-info/pbr.json0000664000175100017510000000005613217007767022654 0ustar zuulzuul00000000000000{"git_version": "00b8171", "is_release": true}monasca-statsd-1.9.0/monasca_statsd.egg-info/dependency_links.txt0000664000175100017510000000000113217007767025243 0ustar zuulzuul00000000000000 monasca-statsd-1.9.0/monasca_statsd.egg-info/SOURCES.txt0000664000175100017510000000127613217007770023061 0ustar zuulzuul00000000000000.coveragerc .testr.conf .zuul.yaml AUTHORS ChangeLog LICENSE README.md Rakefile mkdocs.yml requirements.txt setup.cfg setup.py test-requirements.txt tox.ini 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 tests/__init__.py tests/test_monascastatsd.pymonasca-statsd-1.9.0/monasca_statsd.egg-info/requires.txt0000664000175100017510000000001413217007767023570 0ustar zuulzuul00000000000000six>=1.10.0 monasca-statsd-1.9.0/monasca_statsd.egg-info/not-zip-safe0000664000175100017510000000000113217007754023417 0ustar zuulzuul00000000000000 monasca-statsd-1.9.0/tox.ini0000666000175100017510000000301113217007600015772 0ustar zuulzuul00000000000000[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 [testenv:py27] basepython = python2.7 commands = {[testenv]commands} ostestr {posargs} [testenv:py35] basepython = python3.5 commands = {[testenv]commands} ostestr {posargs} [testenv:cover] basepython = python2.7 commands = {[testenv]commands} coverage erase python setup.py test --coverage --testr-args='{posargs}' --coverage-package-name=monascastatsd coverage report [testenv:debug] commands = {[testenv]commands} oslo_debug_helper -t {toxinidir}/tests {posargs} [testenv:docs] 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 = 120 monasca-statsd-1.9.0/monascastatsd/0000775000175100017510000000000013217007770017336 5ustar zuulzuul00000000000000monasca-statsd-1.9.0/monascastatsd/client.py0000666000175100017510000001174313217007600021166 0ustar zuulzuul00000000000000# (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.9.0/monascastatsd/__init__.py0000666000175100017510000000203313217007600021437 0ustar zuulzuul00000000000000# 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.9.0/monascastatsd/gauge.py0000666000175100017510000000611313217007600020773 0ustar zuulzuul00000000000000# (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.9.0/monascastatsd/common.py0000666000175100017510000000163113217007600021173 0ustar zuulzuul00000000000000# 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.9.0/monascastatsd/metricbase.py0000666000175100017510000000547113217007600022027 0ustar zuulzuul00000000000000# (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.9.0/monascastatsd/counter.py0000666000175100017510000000754713217007600021376 0ustar zuulzuul00000000000000# (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.9.0/monascastatsd/connection.py0000666000175100017510000001311413217007600022041 0ustar zuulzuul00000000000000# (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.9.0/monascastatsd/timer.py0000666000175100017510000001122613217007600021024 0ustar zuulzuul00000000000000# (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)