├── .gitignore ├── .travis.yml ├── AUTHORS.rst ├── CHANGES.rst ├── LICENSE ├── MANIFEST.in ├── README.rst ├── TODO.rst ├── docs ├── CHANGES.rst ├── Makefile ├── README.rst ├── api │ ├── defaults.rst │ ├── fields.rst │ ├── index.rst │ ├── mmap.rst │ ├── models.rst │ └── reader.rst ├── authors.rst ├── conf.py ├── dev │ ├── format.rst │ ├── format2.rst │ ├── index.rst │ ├── scrapped.rst │ ├── started.rst │ └── todo.rst ├── history.rst ├── index.rst └── make.bat ├── examples ├── __init__.py ├── basic.py └── basic_flask.py ├── mmstats ├── __init__.py ├── _libgettid.c ├── _mmap.py ├── clean.py ├── defaults.py ├── fields.py ├── libgettid.py ├── mmash.py ├── mmash_settings.py ├── models.py ├── pollstats.py ├── reader.py ├── slurpstats.py ├── static │ ├── base.css │ ├── jquery.flot.js │ └── jquery.js └── templates │ ├── graph.html │ └── index.html ├── run_flask_example ├── setup.py └── tests ├── __init__.py ├── base.py ├── test_mmap.py ├── test_mmstats.py ├── test_naming.py └── test_types.py /.gitignore: -------------------------------------------------------------------------------- 1 | .noseids 2 | *.egg 3 | *.egg-info 4 | *.orig 5 | *.pyc 6 | *.so 7 | local 8 | local_mmash_settings.py 9 | mmstats-test* 10 | bin 11 | build 12 | dist 13 | docs/_build 14 | include 15 | lib 16 | man 17 | share 18 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - 2.6 4 | - 2.7 5 | script: python setup.py test 6 | -------------------------------------------------------------------------------- /AUTHORS.rst: -------------------------------------------------------------------------------- 1 | Contributors 2 | ============ 3 | 4 | Copyright 2012 Urban Airship and contributors 5 | 6 | Developers 7 | ---------- 8 | 9 | * Dan Colish 10 | * Jeff Forcier - https://github.com/bitprophet 11 | * Fredrik Håård - https://github.com/haard 12 | * Adam Lowry 13 | * Santiago Piccinini - https://github.com/spiccinini 14 | * Michael Schurter (creator/lead) 15 | 16 | Reviewers 17 | --------- 18 | 19 | * Niall Kelly 20 | -------------------------------------------------------------------------------- /CHANGES.rst: -------------------------------------------------------------------------------- 1 | History 2 | ======= 3 | 4 | 0.8.0 5 | ----- 6 | 7 | * ``MmStats.remove`` now removes all files for a PID if you use the TID in the 8 | filenames (thanks @bitprophet!) 9 | * *mmash* now prepends ``MMSTATS_PATH`` to ``?glob=...`` parameters so users 10 | can't traverse the filesystem. 11 | * Javascript fixes for *mmash*'s graphs (thanks @spiccinini!) 12 | * Handle broken pipes in *slurpstats* 13 | 14 | 0.7.2 "Mr. Clean" released 2012-12-12 15 | ------------------------------------- 16 | 17 | * `cleanstats` now cleans mmstats files for alive PIDs that are owned by other 18 | users. 19 | * Minor cleanups to tests 20 | 21 | 0.7.1 "Mash Tun" released 2012-11-19 22 | ------------------------------------ 23 | 24 | * ``cleanstats`` now defaults to ``DEFAULT_GLOB`` if no files are passed on the 25 | command line 26 | * ``CounterField.inc(n=...)`` has been deprecated in favor of 27 | ``CounterField.incr(amount=...)`` 28 | * *mmash* Improvements 29 | 30 | * Added ``nonzero-avg`` and ``nonzero-min`` aggregators to mmash to filter 0s 31 | out of aggregated metrics. 32 | * Added a ``glob`` query parameter to ``/stats/`` to filter which 33 | mmstats files are included in the stats 34 | * Backward incompatible change: switched ``/stats/`` to return a JSON Object 35 | instead of an array. The array is now the value of the ``stats`` key. 36 | 37 | * Minor documentation and code cleanups 38 | 39 | 0.7.0 "Local Artisanal Stats" released 2012-10-02 40 | ------------------------------------------------- 41 | 42 | * Per-thread model instances are created automatically - no need to manually 43 | create one per thread 44 | * Backward incompatible change to naming templates; they now use str.format 45 | style substitutions: 46 | 47 | * New: ``{CMD}`` - Current process name 48 | * ``%PID%`` -> ``{PID}`` 49 | * ``%TID%`` -> ``{TID}`` 50 | 51 | 52 | 0.6.2 "Graphtastic" released 2012-03-23 53 | --------------------------------------- 54 | 55 | * Added live graphing of numeric metrics thanks to @haard's work at PyCon 56 | * Documentation improvements 57 | 58 | 0.6.1 "MANIFEST.out" released 2012-03-08 59 | ---------------------------------------- 60 | 61 | * Fix packaging issue 62 | 63 | 0.6.0 "PyCon 2012" released 2012-03-08 64 | -------------------------------------- 65 | 66 | * [API CHANGE] - MovingAverageField's kwarg changed from window_size => size 67 | * Refactored __init__.py into fields, models, and default (and imported public 68 | bits into __init__) 69 | * Added TimerField (MovingAverageField + context manager) 70 | * Added docs (don't get too excited, just a start) 71 | 72 | 0.5.0 "100% More Average" released 2012-02-25 73 | --------------------------------------------- 74 | 75 | * [API CHANGE] - RunningAverage field is now AverageField 76 | * Added MovingAverageField with window_size=100 parameter 77 | * Tests can now be run via "python setup.py test" 78 | 79 | 0.4.1 "Derpstats" released 2012-01-31 80 | ------------------------------------- 81 | 82 | * Fixed pollstats 83 | * Updated README slightly 84 | 85 | 0.4.0 "On the Road to Pycon" released 2012-01-17 86 | ------------------------------------------------ 87 | 88 | * Added clean module and cleanstats script to clean stale mmstat files 89 | * Added path kwarg to MmStats class to allow easy path overriding 90 | * Added StringField for UTF-8 encoded strings 91 | * Added StaticFloatField & StaticDoubleField 92 | * Added created UNIX timestamp (sys.created) to default MmStats class 93 | * Moved all modules into mmstats package 94 | * Fixed mmash template packaging 95 | * Fixed test mmstat file cleanup 96 | * Refactored reading code into mmstats.reader module 97 | 98 | 0.3.12 "Meow" released 2011-11-29 99 | --------------------------------- 100 | 101 | * Use ctypes.get_errno() instead of Linux specific wrapper 102 | 103 | 0.3.11 "Rawr" released 2011-11-29 104 | --------------------------------- 105 | 106 | * Fix libc loading on OSX 107 | 108 | 0.3.10 "π²" released 2011-11-28 109 | ------------------------------- 110 | 111 | * PyPy support (switched from ctypes._CData.from_buffer to .from_address) 112 | * Multiple calls to MmStats().remove() no longer error (makes testing easier) 113 | 114 | 0.3.9 "MLIT" released 1970-01-01 115 | -------------------------------- 116 | 117 | * Mistag of 0.3.8 118 | 119 | 0.3.8 "Hapiness" released 2011-11-20 120 | ------------------------------------ 121 | 122 | * Allow filename templating with %PID% and %TID% placeholders 123 | * Allow setting filename template via MMSTATS_FILES environment variable 124 | * Improved docs slightly 125 | * Fixed Ctrl-Cing run_flask_example script 126 | * Fixed 64 bit integer fields on 32 bit platforms 127 | * Fixed StaticInt64Field (was actually a uint64 field before) 128 | * Fixed slurpstats debug output (always showed first 40 bytes of file) 129 | * Strip newlines from org.python.version 130 | 131 | 0.3.7 "Depressive Realism is for Winners" released 2011-11-17 132 | ------------------------------------------------------------- 133 | 134 | * Add pollstats utility (similar to dstat/vmstat) 135 | * Cleanup development/testing section of the README 136 | * Slight improvements to basic flask integration example 137 | 138 | 0.3.6 "The M is for Mongo" released 2011-11-09 139 | ---------------------------------------------- 140 | 141 | * Allow setting the value of CounterFields 142 | 143 | 0.3.5 "Ornery Orangutan" released 2011-10-20 144 | -------------------------------------------- 145 | 146 | * Added a running average field 147 | * Made mmash more configurable and added a console entry point 148 | * Updated TODO 149 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2011 by Michael Schurter. 2 | 3 | Some rights reserved. 4 | 5 | Redistribution and use in source and binary forms of the software as well 6 | as documentation, with or without modification, are permitted provided 7 | that the following conditions are met: 8 | 9 | * Redistributions of source code must retain the above copyright 10 | notice, this list of conditions and the following disclaimer. 11 | 12 | * Redistributions in binary form must reproduce the above 13 | copyright notice, this list of conditions and the following 14 | disclaimer in the documentation and/or other materials provided 15 | with the distribution. 16 | 17 | * The names of the contributors may not be used to endorse or 18 | promote products derived from this software without specific 19 | prior written permission. 20 | 21 | THIS SOFTWARE AND DOCUMENTATION IS PROVIDED BY THE COPYRIGHT HOLDERS AND 22 | CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT 23 | NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 24 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 25 | OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 26 | EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 27 | PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 28 | PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 29 | LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 30 | NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 31 | SOFTWARE AND DOCUMENTATION, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH 32 | DAMAGE. 33 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include AUTHORS 2 | include LICENSE 3 | include README.rst 4 | include CHANGES.rst 5 | include TODO.rst 6 | recursive-include mmstats/static * 7 | recursive-include mmstats/templates * 8 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | `Documentation `_ | 2 | `Package `_ | 3 | `Code `_ 4 | 5 | .. image:: https://secure.travis-ci.org/schmichael/mmstats.png?branch=master 6 | :target: http://travis-ci.org/schmichael/mmstats/ 7 | 8 | 9 | **Not under active development** 10 | 11 | 12 | About 13 | ===== 14 | 15 | Mmstats is a way to expose and read diagnostic values and metrics for 16 | applications. 17 | 18 | Think of mmstats as /proc for your application and the readers as procps 19 | utilities. 20 | 21 | This project is a Python implementation, but compatible implementations can be 22 | made in any language (see Goals). 23 | 24 | Discuss at https://groups.google.com/group/python-introspection 25 | 26 | Goals 27 | ----- 28 | 29 | * Separate publishing/writing from consuming/reading tools 30 | * Platform/language independent (a Java writer can be read by a Python tool) 31 | * Predictable performance impact for writers via: 32 | 33 | * No locks (1 writer per thread) 34 | * No syscalls (after instantiation) 35 | * All in userspace 36 | * Reading has no impact on writers 37 | 38 | * Optional persistent (writer can sync anytime) 39 | * 1-way (Publish/consume only; mmstats are not management extensions) 40 | 41 | Usage 42 | ===== 43 | 44 | Requirements 45 | ------------ 46 | 47 | CPython 2.6 or 2.7 (Windows is untested) 48 | 49 | PyPy (only tested in 1.7, should be faster in 1.8) 50 | 51 | Using 52 | ----- 53 | 54 | 1. ``easy_install mmstats`` or ``pip install mmstats`` or if you've downloaded 55 | the source: ``python setup.py install`` 56 | 2. Then in your Python project create a sublcass of mmstats.MmStats like 57 | 58 | .. code-block:: python 59 | 60 | import mmstats 61 | 62 | class WebStats(mmstats.MmStats): 63 | status2xx = mmstats.CounterField(label='status.2XX') 64 | status3xx = mmstats.CounterField(label='status.3XX') 65 | status4xx = mmstats.CounterField(label='status.4XX') 66 | status5xx = mmstats.CounterField(label='status.5XX') 67 | last_hit = mmstats.DoubleField(label='timers.last_hit') 68 | 69 | 3. Instantiate it once per process: (instances are automatically thread local) 70 | 71 | .. code-block:: python 72 | 73 | webstats = WebStats(label_prefix='web.stats.') 74 | 75 | 4. Record some data: 76 | 77 | .. code-block:: python 78 | 79 | if response.status_code == 200: 80 | webstats.status2xx.inc() 81 | 82 | webstats.last_hit = time.time() 83 | 84 | 5. Run ``slurpstats`` to read it 85 | 6. Run ``mmash`` to create a web interface for stats 86 | 7. Run ``pollstats -p web.stats.status 2XX,3XX,4XX,5XX /tmp/mmstats-*`` for a 87 | vmstat/dstat like view. 88 | 8. Did a process die unexpectedly and leave around a stale mmstat file? 89 | ``cleanstats /path/to/mmstat/files`` will check to see which files are stale 90 | and remove them. 91 | 92 | 93 | .. include:: CHANGES.rst 94 | :end-before: 0.5.0 95 | -------------------------------------------------------------------------------- /TODO.rst: -------------------------------------------------------------------------------- 1 | ==== 2 | TODO 3 | ==== 4 | 5 | There's always bugs to fix: https://github.com/schmichael/mmstats/issues/ 6 | 7 | * Add API to dynamically add fields to MmStat classes 8 | * Percentiles 9 | * Time based windows for moving averages (eg last 60 seconds) 10 | * Multiple exposed fields (average, mean, and percentiles) from 1 model field 11 | * Add alternative procedural writer API (vs existing declarative models) 12 | * Test severity of race conditions (especially: byte value indicating write 13 | buffer) 14 | * Test performance 15 | * Vary filename based on class name 16 | * Improve mmash (better live graphing, read from multiple paths, etc) 17 | * Include semantic metadata with field types (eg to differentiate an int that's 18 | a datetime from an int that's a counter) 19 | * Logo 20 | -------------------------------------------------------------------------------- /docs/CHANGES.rst: -------------------------------------------------------------------------------- 1 | ../CHANGES.rst -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # Internal variables. 11 | PAPEROPT_a4 = -D latex_paper_size=a4 12 | PAPEROPT_letter = -D latex_paper_size=letter 13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 14 | # the i18n builder cannot share the environment and doctrees with the others 15 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 16 | 17 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 18 | 19 | help: 20 | @echo "Please use \`make ' where is one of" 21 | @echo " html to make standalone HTML files" 22 | @echo " dirhtml to make HTML files named index.html in directories" 23 | @echo " singlehtml to make a single large HTML file" 24 | @echo " pickle to make pickle files" 25 | @echo " json to make JSON files" 26 | @echo " htmlhelp to make HTML files and a HTML help project" 27 | @echo " qthelp to make HTML files and a qthelp project" 28 | @echo " devhelp to make HTML files and a Devhelp project" 29 | @echo " epub to make an epub" 30 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 31 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 32 | @echo " text to make text files" 33 | @echo " man to make manual pages" 34 | @echo " texinfo to make Texinfo files" 35 | @echo " info to make Texinfo files and run them through makeinfo" 36 | @echo " gettext to make PO message catalogs" 37 | @echo " changes to make an overview of all changed/added/deprecated items" 38 | @echo " linkcheck to check all external links for integrity" 39 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 40 | 41 | clean: 42 | -rm -rf $(BUILDDIR)/* 43 | 44 | html: 45 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 46 | @echo 47 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 48 | 49 | dirhtml: 50 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 51 | @echo 52 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 53 | 54 | singlehtml: 55 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 56 | @echo 57 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 58 | 59 | pickle: 60 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 61 | @echo 62 | @echo "Build finished; now you can process the pickle files." 63 | 64 | json: 65 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 66 | @echo 67 | @echo "Build finished; now you can process the JSON files." 68 | 69 | htmlhelp: 70 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 71 | @echo 72 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 73 | ".hhp project file in $(BUILDDIR)/htmlhelp." 74 | 75 | qthelp: 76 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 77 | @echo 78 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 79 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 80 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/MmStats.qhcp" 81 | @echo "To view the help file:" 82 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/MmStats.qhc" 83 | 84 | devhelp: 85 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 86 | @echo 87 | @echo "Build finished." 88 | @echo "To view the help file:" 89 | @echo "# mkdir -p $$HOME/.local/share/devhelp/MmStats" 90 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/MmStats" 91 | @echo "# devhelp" 92 | 93 | epub: 94 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 95 | @echo 96 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 97 | 98 | latex: 99 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 100 | @echo 101 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 102 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 103 | "(use \`make latexpdf' here to do that automatically)." 104 | 105 | latexpdf: 106 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 107 | @echo "Running LaTeX files through pdflatex..." 108 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 109 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 110 | 111 | text: 112 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 113 | @echo 114 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 115 | 116 | man: 117 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 118 | @echo 119 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 120 | 121 | texinfo: 122 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 123 | @echo 124 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 125 | @echo "Run \`make' in that directory to run these through makeinfo" \ 126 | "(use \`make info' here to do that automatically)." 127 | 128 | info: 129 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 130 | @echo "Running Texinfo files through makeinfo..." 131 | make -C $(BUILDDIR)/texinfo info 132 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 133 | 134 | gettext: 135 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 136 | @echo 137 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 138 | 139 | changes: 140 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 141 | @echo 142 | @echo "The overview file is in $(BUILDDIR)/changes." 143 | 144 | linkcheck: 145 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 146 | @echo 147 | @echo "Link check complete; look for any errors in the above output " \ 148 | "or in $(BUILDDIR)/linkcheck/output.txt." 149 | 150 | doctest: 151 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 152 | @echo "Testing of doctests in the sources finished, look at the " \ 153 | "results in $(BUILDDIR)/doctest/output.txt." 154 | -------------------------------------------------------------------------------- /docs/README.rst: -------------------------------------------------------------------------------- 1 | ../README.rst -------------------------------------------------------------------------------- /docs/api/defaults.rst: -------------------------------------------------------------------------------- 1 | Internal Defaults 2 | ================= 3 | 4 | .. automodule:: mmstats.defaults 5 | :members: 6 | -------------------------------------------------------------------------------- /docs/api/fields.rst: -------------------------------------------------------------------------------- 1 | Model Fields 2 | ============ 3 | 4 | .. automodule:: mmstats.fields 5 | :members: 6 | -------------------------------------------------------------------------------- /docs/api/index.rst: -------------------------------------------------------------------------------- 1 | API 2 | === 3 | 4 | .. toctree:: 5 | :maxdepth: 2 6 | 7 | models 8 | fields 9 | reader 10 | defaults 11 | mmap 12 | -------------------------------------------------------------------------------- /docs/api/mmap.rst: -------------------------------------------------------------------------------- 1 | mmap Compatibility Wrapper 2 | ========================== 3 | 4 | .. automodule:: mmstats._mmap 5 | :members: 6 | -------------------------------------------------------------------------------- /docs/api/models.rst: -------------------------------------------------------------------------------- 1 | Models 2 | ====== 3 | 4 | .. automodule:: mmstats.models 5 | :members: 6 | -------------------------------------------------------------------------------- /docs/api/reader.rst: -------------------------------------------------------------------------------- 1 | Reader API 2 | ========== 3 | 4 | .. automodule:: mmstats.reader 5 | :members: 6 | -------------------------------------------------------------------------------- /docs/authors.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../AUTHORS.rst 2 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # MmStats documentation build configuration file, created by 4 | # sphinx-quickstart on Wed Mar 7 20:12:01 2012. 5 | # 6 | # This file is execfile()d with the current directory set to its containing dir. 7 | # 8 | # Note that not all possible configuration values are present in this 9 | # autogenerated file. 10 | # 11 | # All configuration values have a default; values that are commented out 12 | # serve to show the default. 13 | 14 | import sys, os 15 | 16 | # If extensions (or modules to document with autodoc) are in another directory, 17 | # add these directories to sys.path here. If the directory is relative to the 18 | # documentation root, use os.path.abspath to make it absolute, like shown here. 19 | sys.path.insert(0, os.path.abspath('..')) 20 | import mmstats 21 | 22 | # -- General configuration ----------------------------------------------------- 23 | 24 | # If your documentation needs a minimal Sphinx version, state it here. 25 | #needs_sphinx = '1.0' 26 | 27 | # Add any Sphinx extension module names here, as strings. They can be extensions 28 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 29 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.viewcode'] 30 | 31 | # Add any paths that contain templates here, relative to this directory. 32 | templates_path = ['_templates'] 33 | 34 | # The suffix of source filenames. 35 | source_suffix = '.rst' 36 | 37 | # The encoding of source files. 38 | #source_encoding = 'utf-8-sig' 39 | 40 | # The master toctree document. 41 | master_doc = 'index' 42 | 43 | # General information about the project. 44 | project = u'MmStats' 45 | copyright = u'2012, Urban Airship and contributors' 46 | 47 | # The version info for the project you're documenting, acts as replacement for 48 | # |version| and |release|, also used in various other places throughout the 49 | # built documents. 50 | # 51 | # The short X.Y version. 52 | version = '.'.join(mmstats.version.split('.')[:2]) 53 | # The full version, including alpha/beta/rc tags. 54 | release = mmstats.version 55 | 56 | # The language for content autogenerated by Sphinx. Refer to documentation 57 | # for a list of supported languages. 58 | #language = None 59 | 60 | # There are two options for replacing |today|: either, you set today to some 61 | # non-false value, then it is used: 62 | #today = '' 63 | # Else, today_fmt is used as the format for a strftime call. 64 | #today_fmt = '%B %d, %Y' 65 | 66 | # List of patterns, relative to source directory, that match files and 67 | # directories to ignore when looking for source files. 68 | exclude_patterns = ['_build'] 69 | 70 | # The reST default role (used for this markup: `text`) to use for all documents. 71 | #default_role = None 72 | 73 | # If true, '()' will be appended to :func: etc. cross-reference text. 74 | #add_function_parentheses = True 75 | 76 | # If true, the current module name will be prepended to all description 77 | # unit titles (such as .. function::). 78 | #add_module_names = True 79 | 80 | # If true, sectionauthor and moduleauthor directives will be shown in the 81 | # output. They are ignored by default. 82 | #show_authors = False 83 | 84 | # The name of the Pygments (syntax highlighting) style to use. 85 | pygments_style = 'sphinx' 86 | 87 | # A list of ignored prefixes for module index sorting. 88 | #modindex_common_prefix = [] 89 | 90 | 91 | # -- Options for HTML output --------------------------------------------------- 92 | 93 | # The theme to use for HTML and HTML Help pages. See the documentation for 94 | # a list of builtin themes. 95 | html_theme = 'default' 96 | 97 | # Theme options are theme-specific and customize the look and feel of a theme 98 | # further. For a list of options available for each theme, see the 99 | # documentation. 100 | #html_theme_options = {} 101 | 102 | # Add any paths that contain custom themes here, relative to this directory. 103 | #html_theme_path = [] 104 | 105 | # The name for this set of Sphinx documents. If None, it defaults to 106 | # " v documentation". 107 | #html_title = None 108 | 109 | # A shorter title for the navigation bar. Default is the same as html_title. 110 | #html_short_title = None 111 | 112 | # The name of an image file (relative to this directory) to place at the top 113 | # of the sidebar. 114 | #html_logo = None 115 | 116 | # The name of an image file (within the static path) to use as favicon of the 117 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 118 | # pixels large. 119 | #html_favicon = None 120 | 121 | # Add any paths that contain custom static files (such as style sheets) here, 122 | # relative to this directory. They are copied after the builtin static files, 123 | # so a file named "default.css" will overwrite the builtin "default.css". 124 | html_static_path = ['_static'] 125 | 126 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 127 | # using the given strftime format. 128 | #html_last_updated_fmt = '%b %d, %Y' 129 | 130 | # If true, SmartyPants will be used to convert quotes and dashes to 131 | # typographically correct entities. 132 | #html_use_smartypants = True 133 | 134 | # Custom sidebar templates, maps document names to template names. 135 | #html_sidebars = {} 136 | 137 | # Additional templates that should be rendered to pages, maps page names to 138 | # template names. 139 | #html_additional_pages = {} 140 | 141 | # If false, no module index is generated. 142 | #html_domain_indices = True 143 | 144 | # If false, no index is generated. 145 | #html_use_index = True 146 | 147 | # If true, the index is split into individual pages for each letter. 148 | #html_split_index = False 149 | 150 | # If true, links to the reST sources are added to the pages. 151 | #html_show_sourcelink = True 152 | 153 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 154 | #html_show_sphinx = True 155 | 156 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 157 | #html_show_copyright = True 158 | 159 | # If true, an OpenSearch description file will be output, and all pages will 160 | # contain a tag referring to it. The value of this option must be the 161 | # base URL from which the finished HTML is served. 162 | #html_use_opensearch = '' 163 | 164 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 165 | #html_file_suffix = None 166 | 167 | # Output file base name for HTML help builder. 168 | htmlhelp_basename = 'MmStatsdoc' 169 | 170 | 171 | # -- Options for LaTeX output -------------------------------------------------- 172 | 173 | latex_elements = { 174 | # The paper size ('letterpaper' or 'a4paper'). 175 | #'papersize': 'letterpaper', 176 | 177 | # The font size ('10pt', '11pt' or '12pt'). 178 | #'pointsize': '10pt', 179 | 180 | # Additional stuff for the LaTeX preamble. 181 | #'preamble': '', 182 | } 183 | 184 | # Grouping the document tree into LaTeX files. List of tuples 185 | # (source start file, target name, title, author, documentclass [howto/manual]). 186 | latex_documents = [ 187 | ('index', 'MmStats.tex', u'MmStats Documentation', 188 | u'Michael Schurter', 'manual'), 189 | ] 190 | 191 | # The name of an image file (relative to this directory) to place at the top of 192 | # the title page. 193 | #latex_logo = None 194 | 195 | # For "manual" documents, if this is true, then toplevel headings are parts, 196 | # not chapters. 197 | #latex_use_parts = False 198 | 199 | # If true, show page references after internal links. 200 | #latex_show_pagerefs = False 201 | 202 | # If true, show URL addresses after external links. 203 | #latex_show_urls = False 204 | 205 | # Documents to append as an appendix to all manuals. 206 | #latex_appendices = [] 207 | 208 | # If false, no module index is generated. 209 | #latex_domain_indices = True 210 | 211 | 212 | # -- Options for manual page output -------------------------------------------- 213 | 214 | # One entry per manual page. List of tuples 215 | # (source start file, name, description, authors, manual section). 216 | man_pages = [ 217 | ('index', 'mmstats', u'MmStats Documentation', 218 | [u'Michael Schurter'], 1) 219 | ] 220 | 221 | # If true, show URL addresses after external links. 222 | #man_show_urls = False 223 | 224 | 225 | # -- Options for Texinfo output ------------------------------------------------ 226 | 227 | # Grouping the document tree into Texinfo files. List of tuples 228 | # (source start file, target name, title, author, 229 | # dir menu entry, description, category) 230 | texinfo_documents = [ 231 | ('index', 'MmStats', u'MmStats Documentation', 232 | u'Michael Schurter', 'MmStats', 'One line description of project.', 233 | 'Miscellaneous'), 234 | ] 235 | 236 | # Documents to append as an appendix to all manuals. 237 | #texinfo_appendices = [] 238 | 239 | # If false, no module index is generated. 240 | #texinfo_domain_indices = True 241 | 242 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 243 | #texinfo_show_urls = 'footnote' 244 | 245 | 246 | # Example configuration for intersphinx: refer to the Python standard library. 247 | intersphinx_mapping = {'http://docs.python.org/': None} 248 | -------------------------------------------------------------------------------- /docs/dev/format.rst: -------------------------------------------------------------------------------- 1 | mmap Format 2 | =========== 3 | 4 | Structure of version 1 mmstat's mmaps: 5 | 6 | +-------------------+-----------+ 7 | | version number | fields... | 8 | +===================+===========+ 9 | | ``byte`` = ``01`` | ... | 10 | +-------------------+-----------+ 11 | 12 | 13 | Fields 14 | ------ 15 | 16 | There are two types of field structures so far in mmstats: 17 | 18 | #. buffered 19 | #. unbuffered 20 | 21 | Buffered fields use multiple buffers for handling values which cannot be 22 | written atomically. 23 | 24 | Unbuffered structures have ``ff`` in the write buffer field. 25 | 26 | Buffered 27 | ^^^^^^^^ 28 | 29 | +------------+------------+------------+------------+--------------+----------+----------+ 30 | | label size | label | type size | type | write buffer | buffer 1 | buffer 2 | 31 | +============+============+============+============+==============+==========+==========+ 32 | | ``ushort`` | ``char[]`` | ``ushort`` | ``char[]`` | ``byte`` | varies | varies | 33 | +------------+------------+------------+------------+--------------+----------+----------+ 34 | 35 | The buffers field length = sizeof(type) * buffers. 36 | 37 | The current write buffer is referenced by: write_buffer * sizeof(type) 38 | 39 | TODO: field for total number of buffers? 40 | 41 | 42 | Unbuffered 43 | ^^^^^^^^^^ 44 | 45 | +------------+------------+------------+------------+-------------------+---------+ 46 | | label size | label | type size | type | write buffer | value | 47 | +============+============+============+============+===================+=========+ 48 | | ``ushort`` | ``char[]`` | ``ushort`` | ``char[]`` | ``byte`` = ``ff`` | varies | 49 | +------------+------------+------------+------------+-------------------+---------+ 50 | 51 | The value field length = sizeof(type). 52 | -------------------------------------------------------------------------------- /docs/dev/format2.rst: -------------------------------------------------------------------------------- 1 | mmap Format: Version 2 proposal 2 | =============================== 3 | 4 | Structure of version 2 mmstat's mmaps: 5 | 6 | +-------------------+-----------+ 7 | | version number | fields... | 8 | +===================+===========+ 9 | | ``byte`` = ``02`` | ... | 10 | +-------------------+-----------+ 11 | 12 | 13 | Fields 14 | ------ 15 | 16 | There are three classes of field structures so far in mmstats: 17 | 18 | #. buffered 19 | #. unbuffered 20 | #. buffered array 21 | 22 | Buffered fields use multiple buffers for handling values which cannot be 23 | written atomically. 24 | 25 | Unbuffered structures have ``ff`` in the write buffer field. 26 | 27 | Each field has two distinct type definitions -- data type and metric type. 28 | 29 | Example data types: 30 | #. Buffered Unsigned Integer 31 | #. Static Float 32 | #. Buffered Double 33 | #. Buffered Integer Array 34 | #. Static String 35 | 36 | TODO: document data type IDs 37 | 38 | Example metric types: 39 | #. Gauge 40 | #. Counter 41 | #. Informational (what should we call a string output?) 42 | 43 | Each field is prefixed by the length of the entire field data. 44 | 45 | Unbuffered 46 | ^^^^^^^^^^ 47 | 48 | +------------+------------+------------+------------+-------------+---------+ 49 | | field size | label size | label | data type | metric type | value | 50 | +============+============+============+============+=============+=========+ 51 | | ``int32`` | ``ushort`` | ``char[]`` | ``ushort`` | ``ushort`` | varies | 52 | +------------+------------+------------+------------+-------------+---------+ 53 | 54 | Data type is an integer enum for the list of defined types. The value field length = sizeof(type) 55 | 56 | Buffered 57 | ^^^^^^^^ 58 | 59 | +------------+------------+------------+------------+-------------+--------------+----------+----------+ 60 | | field size | label size | label | data type | metric type | write buffer | buffer 1 | buffer 2 | 61 | +============+============+============+============+=============+==============+==========+==========+ 62 | | ``int32`` | ``ushort`` | ``char[]`` | ``ushort`` | ``ushort`` | ``byte`` | varies | varies | 63 | +------------+------------+------------+------------+-------------+--------------+----------+----------+ 64 | 65 | Data type is an integer enum for the list of defined types. The buffers field length = sizeof(type) * buffers. 66 | 67 | The current write buffer is referenced by: write_buffer * sizeof(type) 68 | 69 | TODO: field for total number of buffers? 70 | 71 | Array 72 | ~~~~~ 73 | 74 | +------------+------------+------------+------------+-------------+---------------------+------------+--------+ 75 | | field size | label size | label | data type | metric type | write buffer offset | array size | buffer | 76 | +============+============+============+============+=============+=====================+============+========+ 77 | | ``int32`` | ``ushort`` | ``char[]`` | ``ushort`` | ``ushort`` | ``ushort`` | ``ushort`` | varies | 78 | +------------+------------+------------+------------+-------------+---------------------+------------+--------+ 79 | 80 | An array is made up of ``array size`` + 1 individual buffers, each of length = sizeof(type) 81 | 82 | The buffers field length = sizeof(type) * (array size + 1). 83 | 84 | The current write buffer is referenced by: write_buffer * data size. Readers should ignore that subfield when reading values. The reader should present "beginning" of the array as the first subfield after the write buffer subfield, wrapping around until the write buffer subfield is reached. 85 | -------------------------------------------------------------------------------- /docs/dev/index.rst: -------------------------------------------------------------------------------- 1 | Development 2 | =========== 3 | 4 | .. toctree:: 5 | :maxdepth: 2 6 | 7 | started 8 | todo 9 | format 10 | scrapped 11 | 12 | See :doc:`started` for how to get started hacking on mmstats or 13 | :doc:`todo` for a list of ways you can help. 14 | -------------------------------------------------------------------------------- /docs/dev/scrapped.rst: -------------------------------------------------------------------------------- 1 | ============== 2 | Scrapped Ideas 3 | ============== 4 | 5 | --------------------------------------------------------------- 6 | Compounds Fields where 1 Writer Field = Many Mmap/Reader Fields 7 | --------------------------------------------------------------- 8 | 9 | This seemed like a honking great idea at first. Compound fields would look just 10 | like a mini-MmStat model: 11 | 12 | :: 13 | 14 | class SamplingCounterField(CompoundField): 15 | """Records increments per ms every N increments""" 16 | counter = CounterField() 17 | per_ms = UInt64Field() 18 | 19 | class _Counter(object): 20 | """Implement counter/rate-sampling logic here""" 21 | 22 | def __get__(self, inst, owner): 23 | if inst is None: 24 | return self 25 | return inst._fields[self.key]._counter_instance 26 | 27 | The blocker is that there's no way to atomically update all of the compound 28 | fields. The only way to accomplish this is for compound fields to appear as a 29 | single double buffered field with each component field as a type in the type 30 | signature: 31 | 32 | :: 33 | 34 | class SamplingCounterField(DoubleBufferedField): 35 | initial = ( 36 | CounterField.initial, 37 | UInt64Field.initial, 38 | ) 39 | buffer_type = ( 40 | CounterField.buffer_type, 41 | UInt64Field.buffer_type, 42 | ) 43 | type_signature = ( 44 | CounterField.type_signature + UInt64Field.type_signature 45 | ) 46 | 47 | Obviously an actual implementation should remove the redundant references to 48 | the component types. 49 | 50 | *Note:* Lack of atomicity is not a blocker for exposing fields such as Mean, 51 | Median, and Percentiles. 52 | 53 | *Solution:* Future versions of the mmstats format should support structs as 54 | values instead of just scalars so that a single write buffer offset can point 55 | to multiple values. 56 | 57 | ------------------------ 58 | Metadata metaprogramming 59 | ------------------------ 60 | 61 | To get around having to dynamically creating the structs due to a variable 62 | label size, put the labels in a header index with a pointer to the actual 63 | struct field. 64 | 65 | ------------- 66 | Page Flipping 67 | ------------- 68 | 69 | Store metadata seperate from values. Then store values in multiple pages and 70 | flip between pages for read/write buffering. 71 | -------------------------------------------------------------------------------- /docs/dev/started.rst: -------------------------------------------------------------------------------- 1 | Getting Started 2 | =============== 3 | 4 | It's easiest to develop mmstats within a virtualenv: 5 | 6 | :: 7 | 8 | $ git clone git://github.com/schmichael/mmstats.git 9 | $ cd mmstats 10 | $ virtualenv . 11 | $ source bin/activate 12 | $ python setup.py develop 13 | $ ./run_flask_example # This starts up a sample web app 14 | $ curl http://localhost:5001/ 15 | $ curl http://localhost:5001/500 16 | $ curl http://localhost:5001/status 17 | $ # If you have ab installed: 18 | $ ab -n 50 -c 10 http://localhost:5001/ 19 | 20 | Now to view the stats run the following in a new terminal: 21 | 22 | :: 23 | 24 | $ # To get a raw view of the data: 25 | $ slurpstats mmstats-* 26 | $ # Or start up the web interface: 27 | $ mmash 28 | $ # Run pollstats while ab is running: 29 | $ pollstats -p flask.example. ok,bad,working mmstats-* 30 | 31 | To cleanup stray mmstats files: ``rm mmstats-flask-*`` 32 | 33 | The web interface will automatically reload when you change source files. 34 | 35 | Put static files into static/ and template files into templates/ 36 | 37 | -------- 38 | Testing 39 | -------- 40 | 41 | Feel free to use your favorite test runner like `nose 42 | `_ or `pytest `_ or just 43 | run: 44 | 45 | :: 46 | 47 | $ python setup.py test 48 | 49 | -------------------------------------------------------------------------------- /docs/dev/todo.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../../TODO.rst 2 | -------------------------------------------------------------------------------- /docs/history.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../CHANGES.rst 2 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. MmStats documentation master file, created by 2 | sphinx-quickstart on Wed Mar 7 20:12:01 2012. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | MmStats: Delicious Data 7 | ======================= 8 | 9 | .. include:: README.rst 10 | 11 | Further topics 12 | ============== 13 | 14 | .. toctree:: 15 | :maxdepth: 2 16 | 17 | api/index 18 | dev/index 19 | history 20 | authors 21 | 22 | 23 | Indices and tables 24 | ================== 25 | 26 | * :ref:`genindex` 27 | * :ref:`modindex` 28 | * :ref:`search` 29 | 30 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. linkcheck to check all external links for integrity 37 | echo. doctest to run all doctests embedded in the documentation if enabled 38 | goto end 39 | ) 40 | 41 | if "%1" == "clean" ( 42 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 43 | del /q /s %BUILDDIR%\* 44 | goto end 45 | ) 46 | 47 | if "%1" == "html" ( 48 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 49 | if errorlevel 1 exit /b 1 50 | echo. 51 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 52 | goto end 53 | ) 54 | 55 | if "%1" == "dirhtml" ( 56 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 57 | if errorlevel 1 exit /b 1 58 | echo. 59 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 60 | goto end 61 | ) 62 | 63 | if "%1" == "singlehtml" ( 64 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 65 | if errorlevel 1 exit /b 1 66 | echo. 67 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 68 | goto end 69 | ) 70 | 71 | if "%1" == "pickle" ( 72 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 73 | if errorlevel 1 exit /b 1 74 | echo. 75 | echo.Build finished; now you can process the pickle files. 76 | goto end 77 | ) 78 | 79 | if "%1" == "json" ( 80 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 81 | if errorlevel 1 exit /b 1 82 | echo. 83 | echo.Build finished; now you can process the JSON files. 84 | goto end 85 | ) 86 | 87 | if "%1" == "htmlhelp" ( 88 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 89 | if errorlevel 1 exit /b 1 90 | echo. 91 | echo.Build finished; now you can run HTML Help Workshop with the ^ 92 | .hhp project file in %BUILDDIR%/htmlhelp. 93 | goto end 94 | ) 95 | 96 | if "%1" == "qthelp" ( 97 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 98 | if errorlevel 1 exit /b 1 99 | echo. 100 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 101 | .qhcp project file in %BUILDDIR%/qthelp, like this: 102 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\MmStats.qhcp 103 | echo.To view the help file: 104 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\MmStats.ghc 105 | goto end 106 | ) 107 | 108 | if "%1" == "devhelp" ( 109 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 110 | if errorlevel 1 exit /b 1 111 | echo. 112 | echo.Build finished. 113 | goto end 114 | ) 115 | 116 | if "%1" == "epub" ( 117 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 118 | if errorlevel 1 exit /b 1 119 | echo. 120 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 121 | goto end 122 | ) 123 | 124 | if "%1" == "latex" ( 125 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 129 | goto end 130 | ) 131 | 132 | if "%1" == "text" ( 133 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 134 | if errorlevel 1 exit /b 1 135 | echo. 136 | echo.Build finished. The text files are in %BUILDDIR%/text. 137 | goto end 138 | ) 139 | 140 | if "%1" == "man" ( 141 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 142 | if errorlevel 1 exit /b 1 143 | echo. 144 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 145 | goto end 146 | ) 147 | 148 | if "%1" == "texinfo" ( 149 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 150 | if errorlevel 1 exit /b 1 151 | echo. 152 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 153 | goto end 154 | ) 155 | 156 | if "%1" == "gettext" ( 157 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 158 | if errorlevel 1 exit /b 1 159 | echo. 160 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 161 | goto end 162 | ) 163 | 164 | if "%1" == "changes" ( 165 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 166 | if errorlevel 1 exit /b 1 167 | echo. 168 | echo.The overview file is in %BUILDDIR%/changes. 169 | goto end 170 | ) 171 | 172 | if "%1" == "linkcheck" ( 173 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 174 | if errorlevel 1 exit /b 1 175 | echo. 176 | echo.Link check complete; look for any errors in the above output ^ 177 | or in %BUILDDIR%/linkcheck/output.txt. 178 | goto end 179 | ) 180 | 181 | if "%1" == "doctest" ( 182 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 183 | if errorlevel 1 exit /b 1 184 | echo. 185 | echo.Testing of doctests in the sources finished, look at the ^ 186 | results in %BUILDDIR%/doctest/output.txt. 187 | goto end 188 | ) 189 | 190 | :end 191 | -------------------------------------------------------------------------------- /examples/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/schmichael/mmstats/9b66fa6b696cdffb463eb2ebd88fef779c0c3da9/examples/__init__.py -------------------------------------------------------------------------------- /examples/basic.py: -------------------------------------------------------------------------------- 1 | import os 2 | import mmstats 3 | import libgettid 4 | 5 | 6 | class MyStats(mmstats.BaseMmStats): 7 | pid = mmstats.StaticUIntField(label="sys.pid", value=os.getpid) 8 | tid = mmstats.StaticInt64Field(label="sys.tid", value=libgettid.gettid) 9 | uid = mmstats.StaticUInt64Field(label="sys.uid", value=os.getuid) 10 | gid = mmstats.StaticUInt64Field(label="sys.gid", value=os.getgid) 11 | errors = mmstats.UIntField(label="com.urbanairship.app.errors") 12 | warnings = mmstats.UIntField(label="com.urbanairship.app.warnings") 13 | queries = mmstats.UIntField(label="com.urbanairship.app.queries") 14 | cache_hits = mmstats.UIntField(label="com.urbanairship.app.cache_hits") 15 | cache_misses = mmstats.UIntField(label="com.urbanairship.app.cache_misses") 16 | degraded = mmstats.BoolField(label="com.urbanairship.app.degraded") 17 | foo = mmstats.StaticTextField( 18 | label="com.idealist.app.name", value="webapp") 19 | 20 | stats = MyStats(filename="mmstats-test-mystats") 21 | stats.degraded = True 22 | stats.errors += 1 23 | stats.cache_hits += 1000 24 | assert stats.cache_hits == 1000 25 | -------------------------------------------------------------------------------- /examples/basic_flask.py: -------------------------------------------------------------------------------- 1 | import atexit 2 | import warnings 3 | 4 | import flask 5 | 6 | import mmstats 7 | 8 | 9 | # Make sure the example only uses the latest and greatest 10 | warnings.simplefilter('error') 11 | 12 | 13 | application = app = flask.Flask(__name__) 14 | app.config['DEBUG'] = True 15 | 16 | 17 | class Stats(mmstats.MmStats): 18 | ok = mmstats.CounterField(label="flask.example.ok") 19 | bad = mmstats.CounterField(label="flask.example.bad") 20 | working = mmstats.BoolField(label="flask.example.working") 21 | 22 | stats = Stats(filename='mmstats-flask-example-%PID%') 23 | atexit.register(stats.remove) 24 | 25 | 26 | def set_working(sender): 27 | stats.working = True 28 | flask.request_started.connect(set_working, app) 29 | 30 | def unset_working(sender, response): 31 | stats.working = False 32 | flask.request_finished.connect(unset_working, app) 33 | 34 | def inc_response(sender, response): 35 | if response.status_code == 200: 36 | stats.ok.incr() 37 | elif response.status_code == 500: 38 | stats.bad.incr() 39 | flask.request_finished.connect(inc_response, app) 40 | 41 | 42 | @app.route('/') 43 | def ok(): 44 | return "OK or see /status for a single process's status" 45 | 46 | 47 | @app.route('/500') 48 | def bad(): 49 | return 'oh noes!', 500 50 | 51 | 52 | @app.route('/status') 53 | def status(): 54 | return """\ 55 | 56 | 57 |
58 |             ok:      %s
59 |             bad:     %s
60 |             working: %s
61 |         
62 | 63 | """ % (stats.ok, stats.bad, stats.working) 64 | 65 | 66 | if __name__ == '__main__': 67 | app.run(host='0.0.0.0', port=5001) 68 | -------------------------------------------------------------------------------- /mmstats/__init__.py: -------------------------------------------------------------------------------- 1 | version = __version__ = '0.8.0' 2 | 3 | from .defaults import * 4 | from .fields import * 5 | from .models import * 6 | -------------------------------------------------------------------------------- /mmstats/_libgettid.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int gettid(void); 5 | 6 | int gettid() 7 | { 8 | return syscall(SYS_gettid); 9 | } 10 | -------------------------------------------------------------------------------- /mmstats/_mmap.py: -------------------------------------------------------------------------------- 1 | import collections 2 | import ctypes 3 | import ctypes.util 4 | import errno 5 | libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library('c')) 6 | import mmap as stdlib_mmap 7 | import os 8 | 9 | 10 | PAGESIZE = stdlib_mmap.PAGESIZE 11 | 12 | 13 | MmapInfo = collections.namedtuple('MmapInfo', ('fd', 'size', 'pointer')) 14 | 15 | 16 | def init_mmap(filename, size=PAGESIZE): 17 | """Create an mmap given a location `filename` and minimum `size` in bytes 18 | 19 | Returns an MmapInfo tuple with the file descriptor, actual size, and a 20 | pointer to the begging of the mmap. 21 | 22 | Note that the size returned is rounded up to the nearest PAGESIZE. 23 | """ 24 | # Create new empty file to back memory map on disk 25 | fd = os.open(filename, os.O_CREAT | os.O_TRUNC | os.O_RDWR) 26 | if size > PAGESIZE: 27 | if size % PAGESIZE: 28 | size = size + (PAGESIZE - (size % PAGESIZE)) 29 | else: 30 | size = PAGESIZE 31 | 32 | # Zero out the file 33 | os.ftruncate(fd, size) 34 | m_ptr = mmap(size, fd) 35 | return MmapInfo(fd, size, m_ptr) 36 | 37 | 38 | # Linux consts from /usr/include/bits/mman.h 39 | MS_ASYNC = 1 40 | MS_SYNC = 4 41 | 42 | 43 | libc.mmap.restype = ctypes.c_void_p 44 | libc.mmap.argtypes = [ 45 | ctypes.c_void_p, # address 46 | ctypes.c_size_t, # size of mapping 47 | ctypes.c_int, # protection 48 | ctypes.c_int, # flags 49 | ctypes.c_int, # fd 50 | ctypes.c_int, # offset (needs to be off_t type?) 51 | ] 52 | 53 | 54 | def mmap(size, fd): 55 | m_ptr = libc.mmap(None, 56 | size, 57 | stdlib_mmap.PROT_READ | stdlib_mmap.PROT_WRITE, 58 | stdlib_mmap.MAP_SHARED, 59 | fd, 60 | 0 61 | ) 62 | if m_ptr == -1: 63 | # Error 64 | e = ctypes.get_errno() 65 | raise OSError(e, errno.errorcode[e]) 66 | return m_ptr 67 | 68 | 69 | libc.msync.restype = ctypes.c_int 70 | libc.msync.argtypes = [ 71 | ctypes.c_void_p, # address 72 | ctypes.c_size_t, # size of mapping 73 | ctypes.c_int, # flags 74 | ] 75 | 76 | 77 | def msync(mm_ptr, size, async=False): 78 | if async: 79 | flags = MS_ASYNC 80 | else: 81 | flags = MS_SYNC 82 | status = libc.msync(mm_ptr, size, flags) 83 | if status == -1: 84 | e = ctypes.get_errno() 85 | raise OSError(e, errno.errorcode[e]) 86 | 87 | 88 | libc.munmap.restype = ctypes.c_int 89 | libc.munmap.argtypes = [ 90 | ctypes.c_void_p, # address 91 | ctypes.c_size_t, # size of mapping 92 | ] 93 | 94 | 95 | def munmap(mm_ptr, size): 96 | status = libc.munmap(mm_ptr, size) 97 | if status == -1: 98 | e = ctypes.get_errno() 99 | raise OSError(e, errno.errorcode[e]) 100 | -------------------------------------------------------------------------------- /mmstats/clean.py: -------------------------------------------------------------------------------- 1 | import errno 2 | import glob 3 | import os 4 | import sys 5 | 6 | 7 | from mmstats import defaults, reader as mmstats_reader 8 | 9 | 10 | def clean(files): 11 | alive, removed = 0, 0 12 | for fn in files: 13 | sys.stdout.flush() 14 | if os.path.isdir(fn): 15 | continue 16 | 17 | try: 18 | reader = mmstats_reader.MmStatsReader.from_file(fn) 19 | except mmstats_reader.InvalidMmStatsVersion: 20 | print 'Invalid file: %s' % fn 21 | continue 22 | except IOError as e: 23 | if e.errno == errno.EACCES: 24 | print 'Permission denied: %s' % fn 25 | # Other IOErrors aren't even worth mentioning 26 | continue 27 | 28 | pid = None 29 | for k, v in reader: 30 | if k.endswith('sys.pid'): 31 | pid = v 32 | 33 | if pid is None: 34 | print 'File has no sys.pid entry: %s' % fn 35 | continue 36 | 37 | try: 38 | os.kill(pid, 0) 39 | except OSError as e: 40 | if e.errno == errno.EPERM: 41 | print ('PID %d is alive but owned by another user. Deleting %s' 42 | % (pid, fn)) 43 | elif e.errno == errno.ESRCH: 44 | # 'No such process' means we can safely delete this stale pid 45 | print 'PID %d not found. Deleting %s' % (pid, fn) 46 | else: 47 | # Don't assume it's safe to continue after other OSErrors 48 | raise 49 | else: 50 | # PID is alive and well, leave it alone 51 | alive += 1 52 | continue 53 | 54 | try: 55 | os.remove(fn) 56 | removed += 1 57 | except OSError as e: 58 | print('Could not remove %s: %s' % (fn, str(e))) 59 | print 'Removed %d - %d alive' % (removed, alive) 60 | 61 | 62 | def cli(): 63 | if len(sys.argv) == 1: 64 | clean(glob.iglob(defaults.DEFAULT_GLOB)) 65 | else: 66 | clean(sys.argv[1:]) 67 | 68 | 69 | if __name__ == '__main__': 70 | cli() 71 | -------------------------------------------------------------------------------- /mmstats/defaults.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | import os 3 | import tempfile 4 | 5 | 6 | BUFFER_IDX_TYPE = ctypes.c_byte 7 | SIZE_TYPE = ctypes.c_ushort 8 | WRITE_BUFFER_UNUSED = 255 9 | DEFAULT_PATH = os.getenv('MMSTATS_PATH', tempfile.gettempdir()) 10 | DEFAULT_FILENAME = os.getenv('MMSTATS_FILES', '{CMD}-{PID}-{TID}.mmstats') 11 | DEFAULT_GLOB = os.getenv( 12 | 'MMSTATS_GLOB', os.path.join(DEFAULT_PATH, '*.mmstats')) 13 | DEFAULT_STRING_SIZE = 255 14 | -------------------------------------------------------------------------------- /mmstats/fields.py: -------------------------------------------------------------------------------- 1 | import array 2 | import ctypes 3 | import math 4 | import time 5 | import warnings 6 | 7 | from . import defaults 8 | 9 | 10 | # >=2.7 ignores DeprecationWarning by default, mimic that behavior here 11 | warnings.filterwarnings('ignore', category=DeprecationWarning) 12 | 13 | 14 | class DuplicateFieldName(Exception): 15 | """Cannot add 2 fields with the same name to MmStat instances""" 16 | 17 | 18 | def _create_struct(label, type_, type_signature, buffers=None): 19 | """Helper to wrap dynamic Structure subclass creation""" 20 | if isinstance(label, unicode): 21 | label = label.encode('utf8') 22 | 23 | fields = [ 24 | ('label_sz', defaults.SIZE_TYPE), 25 | ('label', ctypes.c_char * len(label)), 26 | ('type_sig_sz', defaults.SIZE_TYPE), 27 | ('type_signature', ctypes.c_char * len(type_signature)), 28 | ('write_buffer', ctypes.c_ubyte), 29 | ] 30 | 31 | if buffers is None: 32 | fields.append(('value', type_)) 33 | else: 34 | fields.append(('buffers', (type_ * buffers))) 35 | 36 | return type("%sStruct" % label.title(), 37 | (ctypes.Structure,), 38 | {'_fields_': fields, '_pack_': 1} 39 | ) 40 | 41 | 42 | class Field(object): 43 | initial = 0 44 | 45 | def __init__(self, label=None): 46 | self._struct = None # initialized in _init 47 | if label: 48 | self.label = label 49 | else: 50 | self.label = None 51 | 52 | def _new(self, state, label_prefix, attrname, buffers=None): 53 | """Creates new data structure for field in state instance""" 54 | # Key is used to reference field state on the parent instance 55 | self.key = attrname 56 | 57 | # Label defaults to attribute name if no label specified 58 | if self.label is None: 59 | state.label = label_prefix + attrname 60 | else: 61 | state.label = label_prefix + self.label 62 | state._StructCls = _create_struct( 63 | state.label, self.buffer_type, 64 | self.type_signature, buffers) 65 | state.size = ctypes.sizeof(state._StructCls) 66 | return state.size 67 | 68 | def _init(self, state, mm_ptr, offset): 69 | """Initializes value of field's data structure""" 70 | state._struct = state._StructCls.from_address(mm_ptr + offset) 71 | state._struct.label_sz = len(state.label) 72 | state._struct.label = state.label 73 | state._struct.type_sig_sz = len(self.type_signature) 74 | state._struct.type_signature = self.type_signature 75 | state._struct.write_buffer = defaults.WRITE_BUFFER_UNUSED 76 | state._struct.value = self.initial 77 | return offset + ctypes.sizeof(state._StructCls) 78 | 79 | @property 80 | def type_signature(self): 81 | return self.buffer_type._type_ 82 | 83 | def __repr__(self): 84 | return '%s(label=%r)' % (self.__class__.__name__, self.label) 85 | 86 | 87 | class NonDataDescriptorMixin(object): 88 | """Mixin to add single buffered __get__ method""" 89 | 90 | def __get__(self, inst, owner): 91 | if inst is None: 92 | return self 93 | return inst._fields[self.key]._struct.value 94 | 95 | 96 | class DataDescriptorMixin(object): 97 | """Mixin to add single buffered __set__ method""" 98 | 99 | def __set__(self, inst, value): 100 | inst._fields[self.key]._struct.value = value 101 | 102 | 103 | class BufferedDescriptorMixin(object): 104 | """\ 105 | Mixin to add double buffered descriptor methods 106 | 107 | Always read/write as double buffering doesn't make sense for readonly 108 | fields 109 | """ 110 | 111 | def __get__(self, inst, owner): 112 | if inst is None: 113 | return self 114 | state = inst._fields[self.key] 115 | # Get from the read buffer 116 | return state._struct.buffers[state._struct.write_buffer ^ 1] 117 | 118 | def __set__(self, inst, value): 119 | state = inst._fields[self.key] 120 | # Set the write buffer 121 | state._struct.buffers[state._struct.write_buffer] = value 122 | # Swap the write buffer 123 | state._struct.write_buffer ^= 1 124 | 125 | 126 | class ReadOnlyField(Field, NonDataDescriptorMixin): 127 | def __init__(self, label=None, value=None): 128 | super(ReadOnlyField, self).__init__(label=label) 129 | self.value = value 130 | 131 | def _init(self, state, mm, offset): 132 | if self.value is None: 133 | # Value can't be None 134 | raise ValueError("value must be set") 135 | elif callable(self.value): 136 | # If value is a callable, resolve it now during initialization 137 | self.value = self.value() 138 | 139 | # Call super to do standard initialization 140 | new_offset = super(ReadOnlyField, self)._init(state, mm, offset) 141 | # Set the static field now 142 | state._struct.value = self.value 143 | 144 | # And return the offset as usual 145 | return new_offset 146 | 147 | 148 | class ReadWriteField(Field, NonDataDescriptorMixin, DataDescriptorMixin): 149 | """Base class for simple writable fields""" 150 | 151 | 152 | class DoubleBufferedField(Field): 153 | """Base class for double buffered writable fields""" 154 | def _new(self, state, label_prefix, attrname): 155 | return super(DoubleBufferedField, self)._new( 156 | state, label_prefix, attrname, buffers=2) 157 | 158 | def _init(self, state, mm_ptr, offset): 159 | state._struct = state._StructCls.from_address(mm_ptr + offset) 160 | state._struct.label_sz = len(state.label) 161 | state._struct.label = state.label 162 | state._struct.type_sig_sz = len(self.type_signature) 163 | state._struct.type_signature = self.type_signature 164 | state._struct.write_buffer = 0 165 | state._struct.buffers = 0, 0 166 | return offset + ctypes.sizeof(state._StructCls) 167 | 168 | 169 | class ComplexDoubleBufferedField(DoubleBufferedField): 170 | """Base Class for fields with complex internal state like Counters 171 | 172 | Set InternalClass in your subclass 173 | """ 174 | InternalClass = None 175 | 176 | def _init(self, state, mm_ptr, offset): 177 | offset = super(ComplexDoubleBufferedField, self)._init( 178 | state, mm_ptr, offset) 179 | self._init_internal(state) 180 | return offset 181 | 182 | def _init_internal(self, state): 183 | if self.InternalClass is None: 184 | raise NotImplementedError( 185 | "Must set %s.InternalClass" % type(self).__name__) 186 | state.internal = self.InternalClass(state) 187 | 188 | def __get__(self, inst, owner): 189 | if inst is None: 190 | return self 191 | return inst._fields[self.key].internal 192 | 193 | 194 | class _InternalFieldInterface(object): 195 | """Base class used by internal field interfaces like counter""" 196 | def __init__(self, state): 197 | self._struct = state._struct 198 | 199 | @property 200 | def value(self): 201 | return self._struct.buffers[self._struct.write_buffer ^ 1] 202 | 203 | @value.setter 204 | def value(self, v): 205 | self._set(v) 206 | 207 | def _set(self, v): 208 | # Set the write buffer 209 | self._struct.buffers[self._struct.write_buffer] = v 210 | # Swap the write buffer 211 | self._struct.write_buffer ^= 1 212 | 213 | 214 | class CounterField(ComplexDoubleBufferedField): 215 | """Counter field supporting an inc() method and value attribute""" 216 | buffer_type = ctypes.c_uint64 217 | type_signature = 'Q' 218 | 219 | class InternalClass(_InternalFieldInterface): 220 | """Internal counter class used by CounterFields""" 221 | def inc(self, n=1): 222 | warnings.warn( 223 | "inc(n=...) is deprecated. Use incr(amount=...)", 224 | DeprecationWarning 225 | ) 226 | self.incr(n) 227 | 228 | def incr(self, amount=1): 229 | """Increment Counter by `amount` (defaults to 1)""" 230 | self._set(self.value + amount) 231 | 232 | 233 | class AverageField(ComplexDoubleBufferedField): 234 | """Average field supporting an add() method and value attribute""" 235 | buffer_type = ctypes.c_double 236 | 237 | class InternalClass(_InternalFieldInterface): 238 | """Internal mean class used by AverageFields""" 239 | 240 | def __init__(self, state): 241 | _InternalFieldInterface.__init__(self, state) 242 | 243 | # To recalculate the mean we need to store the overall count 244 | self._count = 0 245 | # Keep the overall total internally 246 | self._total = 0.0 247 | 248 | def add(self, value): 249 | """Add a new value to the average""" 250 | self._count += 1 251 | self._total += value 252 | self._set(self._total / self._count) 253 | 254 | 255 | class _MovingAverageInternal(_InternalFieldInterface): 256 | def __init__(self, state): 257 | _InternalFieldInterface.__init__(self, state) 258 | 259 | self._max = state.field.size 260 | self._window = array.array('d', [0.0] * self._max) 261 | self._idx = 0 262 | self._full = False 263 | 264 | def add(self, value): 265 | """Add a new value to the moving average""" 266 | self._window[self._idx] = value 267 | if self._full: 268 | self._set(math.fsum(self._window) / self._max) 269 | else: 270 | # Window isn't full, divide by current index 271 | self._set(math.fsum(self._window) / (self._idx + 1)) 272 | 273 | if self._idx == (self._max - 1): 274 | # Reset idx 275 | self._idx = 0 276 | self._full = True 277 | else: 278 | self._idx += 1 279 | 280 | 281 | class MovingAverageField(ComplexDoubleBufferedField): 282 | buffer_type = ctypes.c_double 283 | InternalClass = _MovingAverageInternal 284 | 285 | def __init__(self, size=100, **kwargs): 286 | super(MovingAverageField, self).__init__(**kwargs) 287 | self.size = size 288 | 289 | 290 | class _TimerContext(object): 291 | """Class to wrap timer state""" 292 | def __init__(self, timer=time.time): 293 | self._timer = timer 294 | self.start = timer() 295 | self.end = None 296 | 297 | def get_time(self): 298 | return self._timer() 299 | 300 | @property 301 | def done(self): 302 | """True if timer context has stopped""" 303 | return self.end is not None 304 | 305 | @property 306 | def elapsed(self): 307 | """Returns time elapsed in context""" 308 | if self.done: 309 | return self.end - self.start 310 | else: 311 | return self.get_time() - self.start 312 | 313 | def stop(self): 314 | self.end = self.get_time() 315 | 316 | 317 | class TimerField(MovingAverageField): 318 | """Moving average field that provides a context manager for easy timings 319 | 320 | As a context manager: 321 | 322 | >>> class T(MmStats): 323 | ... timer = TimerField() 324 | >>> t = T() 325 | >>> with t.timer as ctx: 326 | ... assert ctx.elapsed > 0.0 327 | >>> assert t.timer.value > 0.0 328 | >>> assert t.timer.last > 0.0 329 | """ 330 | def __init__(self, timer=time.time, **kwargs): 331 | super(TimerField, self).__init__(**kwargs) 332 | self.timer = timer 333 | 334 | class InternalClass(_MovingAverageInternal): 335 | def __init__(self, state): 336 | _MovingAverageInternal.__init__(self, state) 337 | self._ctx = None 338 | self.timer = state.field.timer 339 | 340 | def start(self): 341 | """Start the timer""" 342 | self._ctx = _TimerContext(self.timer) 343 | 344 | def stop(self): 345 | """Stop the timer""" 346 | self._ctx.stop() 347 | self.add(self._ctx.elapsed) 348 | 349 | def __enter__(self): 350 | self.start() 351 | return self._ctx 352 | 353 | def __exit__(self, exc_type, exc_value, exc_tb): 354 | self.stop() 355 | 356 | @property 357 | def last(self): 358 | """Get the last recorded value""" 359 | if self._ctx is None: 360 | return 0.0 361 | else: 362 | return self._ctx.elapsed 363 | 364 | 365 | class BufferedDescriptorField(DoubleBufferedField, BufferedDescriptorMixin): 366 | """Base class for double buffered descriptor fields""" 367 | 368 | 369 | class UInt64Field(BufferedDescriptorField): 370 | """Unbuffered read-only 64bit Unsigned Integer field""" 371 | buffer_type = ctypes.c_uint64 372 | type_signature = 'Q' 373 | 374 | 375 | class UIntField(BufferedDescriptorField): 376 | """32bit Double Buffered Unsigned Integer field""" 377 | buffer_type = ctypes.c_uint32 378 | type_signature = 'I' 379 | 380 | 381 | class IntField(BufferedDescriptorField): 382 | """32bit Double Buffered Signed Integer field""" 383 | buffer_type = ctypes.c_int32 384 | type_signature = 'i' 385 | 386 | 387 | class ShortField(BufferedDescriptorField): 388 | """16bit Double Buffered Signed Integer field""" 389 | buffer_type = ctypes.c_int16 390 | 391 | 392 | class UShortField(BufferedDescriptorField): 393 | """16bit Double Buffered Unsigned Integer field""" 394 | buffer_type = ctypes.c_uint16 395 | 396 | 397 | class ByteField(ReadWriteField): 398 | """8bit Signed Integer Field""" 399 | buffer_type = ctypes.c_byte 400 | 401 | 402 | class FloatField(BufferedDescriptorField): 403 | """32bit Float Field""" 404 | buffer_type = ctypes.c_float 405 | 406 | 407 | class StaticFloatField(ReadOnlyField): 408 | """Unbuffered read-only 32bit Float field""" 409 | buffer_type = ctypes.c_float 410 | 411 | 412 | class DoubleField(BufferedDescriptorField): 413 | """64bit Double Precision Float Field""" 414 | buffer_type = ctypes.c_double 415 | 416 | 417 | class StaticDoubleField(ReadOnlyField): 418 | """Unbuffered read-only 64bit Float field""" 419 | buffer_type = ctypes.c_double 420 | 421 | 422 | class BoolField(ReadWriteField): 423 | """Boolean Field""" 424 | # Avoid potential ambiguity and marshal bools to 0/1 manually 425 | buffer_type = ctypes.c_byte 426 | type_signature = '?' 427 | 428 | def __init__(self, initial=False, **kwargs): 429 | self.initial = initial 430 | super(BoolField, self).__init__(**kwargs) 431 | 432 | def __get__(self, inst, owner): 433 | if inst is None: 434 | return self 435 | return inst._fields[self.key]._struct.value == 1 436 | 437 | def __set__(self, inst, value): 438 | inst._fields[self.key]._struct.value = 1 if value else 0 439 | 440 | 441 | class StringField(ReadWriteField): 442 | """UTF-8 String Field""" 443 | initial = '' 444 | 445 | def __init__(self, size=defaults.DEFAULT_STRING_SIZE, **kwargs): 446 | self.size = size 447 | self.buffer_type = ctypes.c_char * size 448 | super(StringField, self).__init__(**kwargs) 449 | 450 | @property 451 | def type_signature(self): 452 | return '%ds' % self.size 453 | 454 | def __get__(self, inst, owner): 455 | if inst is None: 456 | return self 457 | return inst._fields[self.key]._struct.value.decode('utf8') 458 | 459 | def __set__(self, inst, value): 460 | if isinstance(value, unicode): 461 | value = value.encode('utf8') 462 | if len(value) > self.size: 463 | # Round trip utf8 trimmed strings to make sure it's stores 464 | # valid utf8 bytes 465 | value = value[:self.size] 466 | value = value.decode('utf8', 'ignore').encode('utf8') 467 | elif len(value) > self.size: 468 | value = value[:self.size] 469 | inst._fields[self.key]._struct.value = value 470 | 471 | 472 | class StaticUIntField(ReadOnlyField): 473 | """Unbuffered read-only 32bit Unsigned Integer field""" 474 | buffer_type = ctypes.c_uint32 475 | type_signature = 'I' 476 | 477 | 478 | class StaticInt64Field(ReadOnlyField): 479 | """Unbuffered read-only 64bit Signed Integer field""" 480 | buffer_type = ctypes.c_int64 481 | type_signature = 'q' 482 | 483 | 484 | class StaticUInt64Field(ReadOnlyField): 485 | """Unbuffered read-only 64bit Unsigned Integer field""" 486 | buffer_type = ctypes.c_uint64 487 | type_signature = 'Q' 488 | 489 | 490 | class StaticTextField(ReadOnlyField): 491 | """Unbuffered read-only UTF-8 encoded String field""" 492 | initial = '' 493 | buffer_type = ctypes.c_char * 256 494 | type_signature = '256s' 495 | -------------------------------------------------------------------------------- /mmstats/libgettid.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | import os 3 | import sys 4 | import threading 5 | 6 | 7 | def _linux_gettid(): 8 | """Return system thread id or pid in single thread process""" 9 | return _libgettid.gettid() 10 | 11 | 12 | def _universal_gettid(): 13 | """Give up and just use Python's threading ident 14 | 15 | Some platforms erroneously return None for the main thread's ident. This 16 | will return 0 instead. 17 | """ 18 | return threading.current_thread().ident or 0 19 | 20 | 21 | if 'linux' in sys.platform: 22 | try: 23 | _PATH = os.path.dirname(os.path.abspath(__file__)) 24 | _libgettid = ctypes.cdll.LoadLibrary( 25 | os.path.join(_PATH, '_libgettid.so')) 26 | _libgettid.gettid.restype = ctypes.c_int 27 | _libgettid.gettid.argtypes = [] 28 | except: 29 | gettid = _universal_gettid 30 | else: 31 | gettid = _linux_gettid 32 | else: 33 | gettid = _universal_gettid 34 | -------------------------------------------------------------------------------- /mmstats/mmash.py: -------------------------------------------------------------------------------- 1 | """mmash - Flask JSON Web API for publishing mmstats""" 2 | from collections import defaultdict 3 | import glob 4 | import operator 5 | import os 6 | import sys 7 | 8 | import flask 9 | 10 | from mmstats import defaults, reader as mmstats_reader 11 | 12 | 13 | app = flask.Flask(__name__) 14 | app.config.from_object('mmstats.mmash_settings') 15 | if 'MMASH_SETTINGS' in os.environ: 16 | app.config.from_envvar('MMASH_SETTINGS') 17 | 18 | 19 | def iter_stats(stats_glob=None): 20 | """Yields a label at a time from every mmstats file in MMSTATS_GLOB""" 21 | if not stats_glob: 22 | stats_glob = app.config['MMSTATS_GLOB'] 23 | elif '..' in stats_glob: 24 | # Don't allow path traversal in custom globs 25 | flask.abort(400) 26 | else: 27 | # Prepend MMSTATS_PATH to beginning of glob 28 | stats_glob = os.path.join(defaults.DEFAULT_PATH, stats_glob) 29 | for fn in glob.iglob(stats_glob): 30 | try: 31 | for label, value in mmstats_reader.MmStatsReader.from_mmap(fn): 32 | yield fn, label, value 33 | except Exception: 34 | continue 35 | 36 | 37 | def find_labels(): 38 | """Returns a set of all available labels""" 39 | labels = set() 40 | for fn, label, value in iter_stats(): 41 | labels.add(label) 42 | return labels 43 | 44 | 45 | @app.route('/stats/') 46 | def stats(): 47 | return flask.jsonify(stats=sorted(find_labels())) 48 | 49 | 50 | @app.route('/graph/') 51 | def graph(): 52 | string_stats = [] 53 | numeric_stats = [] 54 | for fn, label, value in iter_stats(): 55 | stat_data = { 56 | 'label': label, 57 | 'value': value, 58 | 'jsid': label.replace('.', '_'), 59 | } 60 | try: 61 | float(value) 62 | except ValueError: 63 | string_stats.append(stat_data) 64 | else: 65 | numeric_stats.append(stat_data) 66 | return flask.render_template('graph.html', 67 | mmstats_dir=app.config['MMSTATS_GLOB'], 68 | string_stats=sorted(string_stats, key=lambda x: x['label']), 69 | numeric_stats=sorted(numeric_stats, key=lambda x: x['label'])) 70 | 71 | 72 | def _nonzero_avg(values): 73 | """Return the average of ``values`` ignoring 0 values""" 74 | nonzero_values = [v for v in values if v] 75 | return float(sum(nonzero_values)) / len(nonzero_values) 76 | 77 | aggregators = { 78 | 'avg': lambda v: float(sum(v)) / len(v), 79 | 'one': operator.itemgetter(0), 80 | 'max': max, 81 | 'min': min, 82 | 'sum': sum, 83 | 'nonzero-min': lambda vals: min([v for v in vals if v]), 84 | 'nonzero-avg': _nonzero_avg, 85 | } 86 | 87 | 88 | @app.route('/files/', defaults={'glob': ''}) 89 | @app.route('/files/') 90 | def getfiles(glob): 91 | files = set(fn for fn, _, _ in iter_stats(glob)) 92 | return flask.jsonify(files=list(files)) 93 | 94 | 95 | @app.route('/stats/') 96 | def getstat(statname): 97 | stats = defaultdict(list) 98 | exact = flask.request.args.get('exact') 99 | stats_glob = flask.request.args.get('glob') 100 | for fn, label, value in iter_stats(stats_glob): 101 | if exact and label == statname: 102 | stats[label].append(value) 103 | elif label.startswith(statname): 104 | stats[label].append(value) 105 | 106 | aggr = aggregators.get(flask.request.args.get('aggr')) 107 | if aggr: 108 | for label, values in stats.iteritems(): 109 | try: 110 | stats[label] = aggr(values) 111 | except Exception: 112 | flask.abort(400) 113 | 114 | return flask.jsonify(stats) 115 | 116 | 117 | @app.route('/') 118 | def index(): 119 | return flask.render_template( 120 | 'index.html', 121 | mmstats_dir=app.config['MMSTATS_GLOB'], 122 | stats=sorted(find_labels()) 123 | ) 124 | 125 | 126 | def main(): 127 | if len(sys.argv) > 1: 128 | print __doc__ 129 | print 130 | print 'Set MMASH_SETTINGS=path/to/settings.py to change settings.' 131 | return 132 | 133 | app.run(host=app.config['HOST'], 134 | port=app.config['PORT'], 135 | debug=app.config['DEBUG'] 136 | ) 137 | 138 | 139 | if __name__ == '__main__': 140 | main() 141 | -------------------------------------------------------------------------------- /mmstats/mmash_settings.py: -------------------------------------------------------------------------------- 1 | from mmstats import defaults 2 | 3 | MMSTATS_GLOB = defaults.DEFAULT_GLOB 4 | DEBUG = True 5 | HOST = '0.0.0.0' 6 | PORT = 5002 7 | -------------------------------------------------------------------------------- /mmstats/models.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | import glob 3 | import os 4 | import sys 5 | import time 6 | import threading 7 | 8 | from . import fields, libgettid, _mmap 9 | from .defaults import DEFAULT_PATH, DEFAULT_FILENAME 10 | 11 | 12 | removal_lock = threading.Lock() 13 | 14 | 15 | def _expand_filename(path=DEFAULT_PATH, filename=DEFAULT_FILENAME): 16 | """Compute mmap's full path given a `path` and `filename`. 17 | 18 | :param path: path to store mmaped files 19 | :param filename: filename template for mmaped files 20 | :returns: fully expanded path and filename 21 | :rtype: str 22 | 23 | Substitutions documented in :class:`~mmstats.models.BaseMmStats` 24 | """ 25 | substitutions = { 26 | 'CMD': os.path.basename(sys.argv[0]), 27 | 'PID': os.getpid(), 28 | 'TID': libgettid.gettid(), 29 | } 30 | # Format filename and path with substitution variables 31 | filename = filename.format(**substitutions) 32 | path = path.format(**substitutions) 33 | 34 | return os.path.join(path, filename) 35 | 36 | 37 | class FieldState(object): 38 | """Holds field state for each Field instance""" 39 | 40 | def __init__(self, field): 41 | self.field = field 42 | 43 | 44 | class BaseMmStats(threading.local): 45 | """Stats models should inherit from this 46 | 47 | Optionally given a filename or label_prefix, create an MmStats instance 48 | 49 | Both `filename` and `path` support the following variable substiutions: 50 | 51 | * `{CMD}` - name of application (`os.path.basename(sys.argv[0])`) 52 | * `{PID}` - process's PID (`os.getpid()`) 53 | * `{TID}` - thread ID (tries to get it via the `SYS_gettid` syscall but 54 | fallsback to the Python/pthread ID or 0 for truly broken platforms) 55 | 56 | This class is *not threadsafe*, so you should include both {PID} and 57 | {TID} in your filename to ensure the mmaped files don't collide. 58 | """ 59 | 60 | def __init__(self, path=DEFAULT_PATH, filename=DEFAULT_FILENAME, 61 | label_prefix=None): 62 | self._removed = False 63 | 64 | # Setup label prefix 65 | self._label_prefix = '' if label_prefix is None else label_prefix 66 | 67 | self._full_path = _expand_filename(path, filename) 68 | self._filename = filename 69 | self._path = path 70 | 71 | self._offset = 1 72 | 73 | # Store state for this instance's fields 74 | self._fields = {} 75 | 76 | total_size = self._offset 77 | #FIXME This is the *wrong* way to initialize stat fields 78 | for cls in self.__class__.__mro__: 79 | for attrname, attrval in cls.__dict__.items(): 80 | if (attrname not in self._fields 81 | and isinstance(attrval, fields.Field)): 82 | total_size += self._add_field(attrname, attrval) 83 | 84 | self._fd, self._size, self._mm_ptr = _mmap.init_mmap( 85 | self._full_path, size=total_size) 86 | mmap_t = ctypes.c_char * self._size 87 | self._mmap = mmap_t.from_address(self._mm_ptr) 88 | ver = ctypes.c_byte.from_address(self._mm_ptr) 89 | ver.value = 1 # Version number 90 | 91 | # Finally initialize thes stats 92 | self._init_fields(total_size) 93 | 94 | def _add_field(self, name, field): 95 | """Given a name and Field instance, add this field and retun size""" 96 | # Stats need a place to store their per Mmstats instance state 97 | state = self._fields[name] = FieldState(field) 98 | 99 | # Call field._new to determine size 100 | return field._new(state, self.label_prefix, name) 101 | 102 | def _init_fields(self, total_size): 103 | """Once all fields have been added, initialize them in mmap""" 104 | 105 | for state in self._fields.values(): 106 | # 2nd Call field._init to initialize new stat 107 | self._offset = state.field._init(state, self._mm_ptr, self._offset) 108 | 109 | @property 110 | def filename(self): 111 | return self._full_path 112 | 113 | @property 114 | def label_prefix(self): 115 | return self._label_prefix 116 | 117 | @property 118 | def size(self): 119 | return self._size 120 | 121 | def flush(self, async=False): 122 | """Flush mmapped file to disk 123 | 124 | :param async: ``True`` means the call won't wait for the flush to 125 | finish syncing to disk. Defaults to ``False`` 126 | :type async: bool 127 | """ 128 | _mmap.msync(self._mm_ptr, self._size, async) 129 | 130 | def remove(self): 131 | with removal_lock: 132 | # Perform regular removal of this process/thread's own file. 133 | self._remove() 134 | # Then ensure we clean up any forgotten thread-related files, if 135 | # applicable. Ensure {PID} exists, for safety's sake - better to not 136 | # cleanup than to cleanup multiple PIDs' files. 137 | if '{PID}' in self._filename and '{TID}' in self._filename: 138 | self._remove_stale_thread_files() 139 | 140 | def _remove_stale_thread_files(self): 141 | # The originally given (to __init__) filename string, containing 142 | # expansion hints, is preserved in _filename. If it contains {TID} we 143 | # can replace that with a glob expression to catch all TIDS for our 144 | # given PID. 145 | globbed = self._filename.replace('{TID}', '*') 146 | # Re-expand any non-{TID} expansion hints 147 | expanded = _expand_filename(path=self._path, filename=globbed) 148 | # And nuke as appropriate. 149 | for leftover in glob.glob(expanded): 150 | os.remove(leftover) 151 | 152 | def _remove(self): 153 | """Close and remove mmap file - No further stats updates will work""" 154 | if self._removed: 155 | # Make calling more than once a noop 156 | return 157 | _mmap.munmap(self._mm_ptr, self._size) 158 | self._size = None 159 | self._mm_ptr = None 160 | self._mmap = None 161 | os.close(self._fd) 162 | try: 163 | os.remove(self.filename) 164 | except OSError: 165 | # Ignore failed file removals 166 | pass 167 | # Remove fields to prevent segfaults 168 | self._fields = {} 169 | self._removed = True 170 | 171 | 172 | class MmStats(BaseMmStats): 173 | """Mmstats default model base class 174 | 175 | Just subclass, add your own fields, and instantiate: 176 | 177 | >>> from mmstats.models import MmStats 178 | >>> from mmstats.fields import CounterField 179 | >>> class MyStats(MmStats): 180 | ... errors = CounterField() 181 | ... 182 | >>> stats = MyStats() 183 | >>> stats.errors.incr() 184 | >>> stats.errors.value 185 | 1L 186 | """ 187 | pid = fields.StaticUIntField(label="sys.pid", value=os.getpid) 188 | tid = fields.StaticInt64Field(label="sys.tid", value=libgettid.gettid) 189 | uid = fields.StaticUInt64Field(label="sys.uid", value=os.getuid) 190 | gid = fields.StaticUInt64Field(label="sys.gid", value=os.getgid) 191 | python_version = fields.StaticTextField(label="org.python.version", 192 | value=lambda: sys.version.replace("\n", "")) 193 | created = fields.StaticDoubleField(label="sys.created", value=time.time) 194 | -------------------------------------------------------------------------------- /mmstats/pollstats.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """pollstats - vmstat/dstat like CLI for mmstats 3 | 4 | pollstats [options] ... 5 | """ 6 | import argparse 7 | import collections 8 | import mmap 9 | import os 10 | import struct 11 | import sys 12 | import time 13 | 14 | import pkg_resources 15 | 16 | from mmstats import reader 17 | 18 | 19 | VERSION = pkg_resources.require('mmstats')[0].version 20 | WARN_LEVEL = 1 21 | INFO_LEVEL = 2 22 | DEBUG_LEVEL = 3 23 | 24 | ansi = { 25 | 'black': '\033[0;30m', 26 | 'darkred': '\033[0;31m', 27 | 'darkgreen': '\033[0;32m', 28 | 'darkyellow': '\033[0;33m', 29 | 'darkblue': '\033[0;34m', 30 | 'darkmagenta': '\033[0;35m', 31 | 'darkcyan': '\033[0;36m', 32 | 'gray': '\033[0;37m', 33 | 34 | 'darkgray': '\033[1;30m', 35 | 'red': '\033[1;31m', 36 | 'green': '\033[1;32m', 37 | 'yellow': '\033[1;33m', 38 | 'blue': '\033[1;34m', 39 | 'magenta': '\033[1;35m', 40 | 'cyan': '\033[1;36m', 41 | 'white': '\033[1;37m', 42 | 43 | 'blackbg': '\033[40m', 44 | 'redbg': '\033[41m', 45 | 'greenbg': '\033[42m', 46 | 'yellowbg': '\033[43m', 47 | 'bluebg': '\033[44m', 48 | 'magentabg': '\033[45m', 49 | 'cyanbg': '\033[46m', 50 | 'whitebg': '\033[47m', 51 | 52 | 'reset': '\033[0;0m', 53 | 'bold': '\033[1m', 54 | 'reverse': '\033[2m', 55 | 'underline': '\033[4m', 56 | 57 | 'clear': '\033[2J', 58 | # 'clearline': '\033[K', 59 | 'clearline': '\033[2K', 60 | # 'save': '\033[s', 61 | # 'restore': '\033[u', 62 | 'save': '\0337', 63 | 'restore': '\0338', 64 | 'linewrap': '\033[7h', 65 | 'nolinewrap': '\033[7l', 66 | 67 | 'up': '\033[1A', 68 | 'down': '\033[1B', 69 | 'right': '\033[1C', 70 | 'left': '\033[1D', 71 | 72 | 'default': '\033[0;0m', 73 | } 74 | 75 | 76 | opts = argparse.ArgumentParser() 77 | opts.add_argument('-c', '--count', type=int) 78 | opts.add_argument('-d', '--delay', type=int, default=1) 79 | opts.add_argument('-f', '--filter', nargs='*', default=[]) 80 | opts.add_argument('-n', '--headers', default=20, type=int, 81 | help='print headers every HEADERS lines') 82 | opts.add_argument('-p', '--prefix', default='', help='field prefix') 83 | opts.add_argument('fields', help='Comma seperated list of fields') 84 | opts.add_argument('files', nargs='+') 85 | opts.add_argument('-v', action='append_const', const=1, dest='verbosity', 86 | default=[], help='verbosity: warnings=1, info=2, debug=3') 87 | opts.add_argument('--version', action='version', 88 | version='%%(prog)s %s' % VERSION) 89 | 90 | 91 | def get_console_size(): 92 | """Returns rows, columns for current console""" 93 | #FIXME Only tested on linux 94 | return map(int, os.popen('stty size', 'r').read().split()) 95 | 96 | 97 | def iter_stats(m): 98 | """Yields label, value pairs for the given mmstats map""" 99 | # Hop to the beginning 100 | m.seek(1) 101 | while m[m.tell()] != '\x00': 102 | label_sz = struct.unpack('H', m.read(2))[0] 103 | label = m.read(label_sz) 104 | type_sz = struct.unpack('H', m.read(2))[0] 105 | type_ = m.read(type_sz) 106 | sz = struct.calcsize(type_) 107 | idx = struct.unpack('B', m.read_byte())[0] 108 | if idx == reader.UNBUFFERED_FIELD: 109 | value = struct.unpack(type_, m.read(sz))[0] 110 | else: 111 | idx ^= 1 # Flip bit as the stored buffer is the *write* buffer 112 | buffers = m.read(sz * 2) 113 | offset = sz * idx 114 | value = struct.unpack(type_, buffers[offset:sz+offset])[0] 115 | yield label, value 116 | 117 | 118 | Mmap = collections.namedtuple('Mmap', ('file', 'mmap')) 119 | 120 | 121 | class PollStats(object): 122 | def __init__(self, args): 123 | self.args = args 124 | self.verbosity = len(self.args.verbosity) 125 | self.fields = args.fields.split(',') 126 | self.prefix = args.prefix 127 | if args.prefix: 128 | self.fields = ["%s%s" % (args.prefix, field) 129 | for field in self.fields] 130 | self.last_vals = dict((field, 0) for field in self.fields) 131 | self.files = {} 132 | self._mmap_files() 133 | 134 | # By default filter down to just files that have the given fields 135 | self.key_filters = set(self.fields) 136 | self.kv_filters = set() 137 | for filterstr in args.filter: 138 | if '=' in filterstr: 139 | # Filter on exact key-value pairs 140 | self.kv_filters.add(filterstr.split('=')) 141 | else: 142 | # Filter on presence of keys 143 | self.key_filters.add(filterstr) 144 | 145 | self._filter_mmaps() 146 | self.print_headers() 147 | 148 | def _mmap_files(self): 149 | for fn in set(self.args.files): 150 | try: 151 | f = open(fn, 'rb') 152 | m = mmap.mmap(f.fileno(), 0, prot=mmap.ACCESS_READ) 153 | except Exception: 154 | self.warn('Skipping %s - unable to open' % fn) 155 | continue 156 | 157 | if m.read_byte() == reader.VERSION_1: 158 | self.files[fn] = Mmap(f, m) 159 | else: 160 | m.close() 161 | f.close() 162 | self.warn('Skipping %s - unknown file format' % fn) 163 | 164 | def _filter_mmaps(self): 165 | for fn, (f, m) in self.files.items(): 166 | # By default remove files that don't match filters 167 | remove = True 168 | fields = dict(pair for pair in iter_stats(m)) 169 | for kf in self.key_filters: 170 | for k in fields.iterkeys(): 171 | # Key filters match the start of the key name 172 | if k.startswith(kf): 173 | remove = False 174 | break 175 | if not remove: 176 | break 177 | 178 | if not remove: 179 | # Matched key filter, don't remove and continue on 180 | continue 181 | 182 | # Didn't remove file, check kv_filters 183 | for kf, vf in self.kv_filters: 184 | if kf in fields and fields[kf] == vf: 185 | remove = False 186 | break 187 | 188 | if remove: 189 | # fn didn't match key filter or key/value filter, remove 190 | self.remove_file(fn) 191 | 192 | def remove_file(self, fn): 193 | """Remove file `fn` from open mmstat files""" 194 | m = self.files[fn] 195 | m.file.close() 196 | m.mmap.close() 197 | del self.files[fn] 198 | 199 | def dbg(self, msg): 200 | if self.verbosity >= DEBUG_LEVEL: 201 | print >> sys.stderr, msg 202 | 203 | def warn(self, msg): 204 | if self.verbosity >= WARN_LEVEL: 205 | print >> sys.stderr, msg 206 | 207 | def print_headers(self): 208 | #_, width = get_console_size() 209 | #field_width = (width / len(self.fields)) - 1 210 | width = 20 211 | print '|'.join( 212 | ansi['bold'] + 213 | f.replace(self.prefix, '', 1)[:width].center(width) 214 | + ansi['default'] 215 | for f in self.fields 216 | ) 217 | 218 | def read_once(self): 219 | cur_vals = collections.defaultdict(int) 220 | for _, m in self.files.itervalues(): 221 | mvals = dict(pair for pair in iter_stats(m)) 222 | for field in self.fields: 223 | cur_vals[field] += mvals[field] 224 | 225 | print '|'.join("%s%19d%s " % (ansi['yellow'], 226 | cur_vals[field] - self.last_vals[field], ansi['default']) 227 | for field in self.fields) 228 | self.last_vals = cur_vals 229 | 230 | def run(self): 231 | if self.args.count: 232 | for _ in xrange(self.args.count): 233 | self.read_once() 234 | time.sleep(self.args.delay) 235 | else: 236 | lines_since_header = 0 237 | while 1: 238 | if lines_since_header == self.args.headers: 239 | self.print_headers() 240 | lines_since_header = 0 241 | self.read_once() 242 | lines_since_header += 1 243 | time.sleep(self.args.delay) 244 | 245 | 246 | def main(): 247 | """CLI Entry Point""" 248 | p = PollStats(opts.parse_args()) 249 | try: 250 | p.run() 251 | except KeyboardInterrupt: 252 | return 253 | 254 | if __name__ == '__main__': 255 | main() 256 | -------------------------------------------------------------------------------- /mmstats/reader.py: -------------------------------------------------------------------------------- 1 | """mmstats reader implementation""" 2 | from collections import namedtuple 3 | import mmap 4 | import struct 5 | 6 | 7 | VERSION_1 = '\x01' 8 | UNBUFFERED_FIELD = 255 9 | 10 | 11 | def reader(fmt): 12 | struct_fmt = struct.Struct(fmt) 13 | size = struct.calcsize(fmt) 14 | unpacker = struct_fmt.unpack 15 | 16 | def wrapper(v): 17 | return unpacker(v.read(size))[0] 18 | wrapper.__name__ = 'unpack_' + fmt 19 | 20 | return wrapper 21 | 22 | 23 | read_ushort = reader('H') 24 | read_ubyte = reader('B') 25 | 26 | 27 | Stat = namedtuple('Stat', ('label', 'value')) 28 | 29 | 30 | class InvalidMmStatsVersion(Exception): 31 | """Unsupported mmstats version""" 32 | 33 | 34 | class MmStatsReader(object): 35 | def __init__(self, data): 36 | """`data` should be a file-like object (mmap or file)""" 37 | self.data = data 38 | rawver = self.data.read(1) 39 | if rawver == VERSION_1: 40 | self.version = 1 41 | else: 42 | raise InvalidMmStatsVersion(repr(rawver)) 43 | 44 | @classmethod 45 | def from_file(cls, fn): 46 | return cls(open(fn, 'rb')) 47 | 48 | @classmethod 49 | def from_mmap(cls, fn): 50 | f = open(fn, 'rb') 51 | try: 52 | mmapf = mmap.mmap(f.fileno(), 0, prot=mmap.ACCESS_READ) 53 | except: 54 | f.close() 55 | raise 56 | return cls(mmapf) 57 | 58 | def __iter__(self): 59 | d = self.data 60 | while 1: 61 | raw_label_sz = d.read(2) 62 | if (not raw_label_sz or raw_label_sz == '\x00' or 63 | raw_label_sz == '\x00\x00'): 64 | # EOF 65 | break 66 | label_sz = struct.unpack('H', raw_label_sz)[0] 67 | label = d.read(label_sz).decode('utf8', 'ignore') 68 | type_sz = read_ushort(d) 69 | type_ = d.read(type_sz) 70 | sz = struct.calcsize(type_) 71 | buf_idx = read_ubyte(d) 72 | if buf_idx == UNBUFFERED_FIELD: 73 | value = struct.unpack(type_, d.read(sz))[0] 74 | else: 75 | # Flip bit as the stored buffer is the *write* buffer 76 | buf_idx ^= 1 77 | buffers = d.read(sz * 2) 78 | offset = sz * buf_idx 79 | read_buffer = buffers[offset:(offset + sz)] 80 | value = struct.unpack(type_, read_buffer)[0] 81 | if isinstance(value, str): 82 | # Special case strings as they're \x00 padded 83 | value = value.split('\x00', 1)[0].decode('utf8', 'ignore') 84 | yield Stat(label, value) 85 | 86 | try: 87 | d.close() 88 | except Exception: 89 | # Don't worry about exceptions closing the file 90 | pass 91 | -------------------------------------------------------------------------------- /mmstats/slurpstats.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import errno 3 | import glob 4 | import mmap 5 | import sys 6 | import traceback 7 | 8 | from mmstats import defaults, reader as mmstats_reader 9 | 10 | 11 | def err(*args): 12 | """Laziness""" 13 | sys.stderr.write('%s\n' % ' '.join(map(str, args))) 14 | 15 | 16 | def slurp_stats(full_fn, m): 17 | """mmap parsing mainloop""" 18 | reader = mmstats_reader.MmStatsReader(m) 19 | 20 | print '==>', full_fn 21 | out = [] 22 | label_max = 0 23 | for label, value in reader: 24 | if len(label) > label_max: 25 | label_max = len(label) 26 | out.append((label, value)) 27 | 28 | for label, value in out: 29 | if isinstance(value, str): 30 | value = value.split('\x00', 1)[0] 31 | print (' %-' + str(label_max) + 's %s') % (label, value) 32 | print 33 | 34 | 35 | def main(): 36 | """MmStats CLI Entry point""" 37 | # Accept paths and dirs to read as mmstats files from the command line 38 | stats_files = set() 39 | for arg in sys.argv[1:]: 40 | stats_files.add(arg) 41 | 42 | # Only read from tempdir if no files specified on the command line 43 | if not stats_files: 44 | stats_files = glob.glob(defaults.DEFAULT_GLOB) 45 | 46 | for fn in stats_files: 47 | with open(fn) as f: 48 | mmst = None 49 | try: 50 | mmst = mmap.mmap(f.fileno(), 0, prot=mmap.ACCESS_READ) 51 | slurp_stats(fn, mmst) 52 | except IOError as ex: 53 | if ex.errno == errno.EPIPE: 54 | # A broken pipe (probably) means the process was killed 55 | # while piped to another command (e.g.: grep) - so die 56 | return 57 | else: 58 | err('Error reading: %s' % fn) 59 | err(traceback.format_exc()) 60 | except Exception: 61 | err('Error reading: %s' % fn) 62 | err(traceback.format_exc()) 63 | finally: 64 | if mmst is not None: 65 | mmst.close() 66 | 67 | 68 | if __name__ == '__main__': 69 | main() 70 | -------------------------------------------------------------------------------- /mmstats/static/base.css: -------------------------------------------------------------------------------- 1 | body { 2 | font-family: sans-serif; 3 | } 4 | 5 | div.hidden { 6 | display: none; 7 | } -------------------------------------------------------------------------------- /mmstats/templates/graph.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 8 | 10 | 11 | mmash for {{ mmstats_dir }} 12 | 13 | 14 |

All non-numeric values

15 |
16 | {% for stat in string_stats %} 17 |
{{ stat.label }}
18 |
{{ stat.value }}
19 | 20 | {% else %} 21 |

No string stats found

22 | {% endfor %} 23 |
24 |

Numeric values

25 | 26 |
27 |

Plotting and update parameters

28 |

Time between samples: milliseconds

30 |

Samples to show in plot:

32 |

Samples to use for rolling avarage:

34 |
35 |

Numeric values

36 | {% for stat in numeric_stats %} 37 |
38 |

39 | 41 | 42 | 44 | 46 |

47 | 49 |
50 | {% endfor %} 51 | 52 | 53 | 54 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | -------------------------------------------------------------------------------- /mmstats/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | mmash for {{ mmstats_dir }} 7 | 8 | 9 | View with plots and polling 10 |
    11 | {% for stat in stats %} 12 |
  • 13 | {{ stat }} 14 |
  • 15 | {% else %} 16 |

    No stats found

    17 | {% endfor %} 18 |
19 | 20 | 21 | -------------------------------------------------------------------------------- /run_flask_example: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | pip install -q gunicorn blinker 3 | echo "Running a basic flask app via gunicorn with 4 processes to demonstrate" 4 | echo "cross-process metric aggregation" 5 | export MMSTATS_PATH=$(pwd) 6 | exec gunicorn -b 0.0.0.0:5001 -w 4 examples.basic_flask 7 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | from setuptools import setup 4 | from setuptools.extension import Extension 5 | 6 | #XXX gettid only works on Linux, don't bother else 7 | if 'linux' in sys.platform: 8 | exts = [Extension('mmstats._libgettid', sources=['mmstats/_libgettid.c'])] 9 | else: 10 | exts = [] 11 | 12 | requirements = ['Flask'] 13 | 14 | 15 | try: 16 | import argparse 17 | except ImportError: 18 | # We're probably on Python <2.7, add argparse as a requirement 19 | requirements.append('argparse') 20 | 21 | import mmstats 22 | 23 | setup( 24 | name='mmstats', 25 | url='https://github.com/schmichael/mmstats', 26 | version=mmstats.__version__, 27 | license='APLv2', 28 | author='Michael Schurter', 29 | author_email='m@schmichael.com', 30 | description='Stat, metric, and diagnostic publishing and consuming tools', 31 | long_description=open('README.rst').read(), 32 | packages=['mmstats'], 33 | include_package_data=True, 34 | entry_points={ 35 | 'console_scripts': [ 36 | 'mmash=mmstats.mmash:main', 37 | 'slurpstats=mmstats.slurpstats:main', 38 | 'pollstats=mmstats.pollstats:main', 39 | 'cleanstats=mmstats.clean:cli', 40 | ], 41 | }, 42 | ext_modules=exts, 43 | test_suite='tests', 44 | install_requires=requirements, 45 | classifiers=['License :: OSI Approved :: Apache Software License'], 46 | # It might actually be zip-safe, I just hate eggs. File an issue or pull 47 | # request if mmstats is actually zip_safe and you care 48 | zip_safe=False 49 | ) 50 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/schmichael/mmstats/9b66fa6b696cdffb463eb2ebd88fef779c0c3da9/tests/__init__.py -------------------------------------------------------------------------------- /tests/base.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | import glob 4 | import os 5 | 6 | import mmstats 7 | 8 | 9 | class MmstatsTestCase(unittest.TestCase): 10 | @property 11 | def files(self): 12 | return glob.glob(os.path.join(self.path, 'test*.mmstats')) 13 | 14 | def setUp(self): 15 | super(MmstatsTestCase, self).setUp() 16 | self.path = mmstats.DEFAULT_PATH 17 | 18 | # Clean out stale mmstats files 19 | for fn in self.files: 20 | try: 21 | os.remove(fn) 22 | pass 23 | except OSError: 24 | print 'Could not remove: %s' % fn 25 | 26 | def tearDown(self): 27 | # clean the dir after tests 28 | for fn in self.files: 29 | try: 30 | os.remove(fn) 31 | pass 32 | except OSError: 33 | continue 34 | -------------------------------------------------------------------------------- /tests/test_mmap.py: -------------------------------------------------------------------------------- 1 | from . import base 2 | 3 | import ctypes 4 | import os 5 | 6 | import mmstats 7 | from mmstats import _mmap 8 | 9 | 10 | class TestMmap(base.MmstatsTestCase): 11 | 12 | def test_pagesize(self): 13 | """PAGESIZE > 0""" 14 | self.assertTrue(_mmap.PAGESIZE > 0, _mmap.PAGESIZE) 15 | 16 | def test_mmap_creation(self): 17 | expected_fn = os.path.join(self.path, 'test_init_alt_name.mmstats') 18 | self.assertFalse(os.path.exists(expected_fn)) 19 | 20 | _, sz, m = _mmap.init_mmap(expected_fn) 21 | self.assertTrue(os.path.exists(expected_fn)) 22 | 23 | def test_size_adjusting1(self): 24 | """mmapped files must be at least PAGESIZE in size""" 25 | fn = os.path.join(self.path, 'test_size_adjusting-1.mmstats') 26 | _, sz, m = _mmap.init_mmap(fn, size=1) 27 | 28 | self.assertEqual(sz, _mmap.PAGESIZE) 29 | for i in range(sz): 30 | self.assertEqual(ctypes.c_char.from_address(m+i).value, '\x00') 31 | 32 | def test_size_adjusting2(self): 33 | """mmapped files must be multiples of PAGESIZE""" 34 | fn = os.path.join(self.path, 'test_size_adjusting-2.mmstats') 35 | _, sz, m = _mmap.init_mmap(fn, size=(_mmap.PAGESIZE + 1)) 36 | 37 | self.assertEqual(sz, _mmap.PAGESIZE * 2) 38 | for i in range(sz): 39 | self.assertEqual(ctypes.c_char.from_address(m+i).value, '\x00') 40 | 41 | def test_truncate(self): 42 | """mmapped files must be initialized with null bytes""" 43 | fn = os.path.join(self.path, 'test_truncate.mmstats') 44 | _, sz, m = _mmap.init_mmap(fn) 45 | 46 | first_byte = ctypes.c_char.from_address(m) 47 | first_byte.value = 'X' 48 | 49 | reopened_file = open(fn) 50 | self.assertEqual(reopened_file.read(1), 'X') 51 | self.assertEqual(reopened_file.read(1), '\x00') 52 | 53 | def test_remove(self): 54 | """Calling remove() on an MmStat instance should remove the file""" 55 | class TestStat(mmstats.MmStats): 56 | b = mmstats.BoolField() 57 | 58 | fn = os.path.join(self.path, 'test_remove.mmstats') 59 | ts = TestStat(filename=fn) 60 | ts.b = True 61 | self.assertTrue(ts.b) 62 | self.assertTrue(os.path.exists(fn), fn) 63 | ts.remove() 64 | self.assertFalse(os.path.exists(fn)) 65 | # Trying to access the mmap after it's been removed should raise an 66 | # exception but *not* segault 67 | self.assertRaises(Exception, getattr, ts, 'b') 68 | -------------------------------------------------------------------------------- /tests/test_mmstats.py: -------------------------------------------------------------------------------- 1 | from . import base 2 | 3 | import threading 4 | import uuid 5 | 6 | import mmstats 7 | from mmstats import _mmap 8 | 9 | 10 | class TestMmStats(base.MmstatsTestCase): 11 | def test_class_instances(self): 12 | """You can have 2 instances of an MmStats model without shared state""" 13 | class LaserStats(mmstats.MmStats): 14 | blue = mmstats.UIntField() 15 | red = mmstats.UIntField() 16 | 17 | a = LaserStats(filename='test-laserstats-a.mmstats') 18 | b = LaserStats(filename='test-laserstats-b.mmstats') 19 | 20 | a.blue = 1 21 | a.red = 2 22 | b.blue = 42 23 | 24 | self.assertEqual(a.blue, 1) 25 | self.assertEqual(a.red, 2) 26 | self.assertEqual(b.blue, 42) 27 | self.assertEqual(b.red, 0) 28 | 29 | def test_thread_cleanup(self): 30 | """ 31 | Per-thread mmstats files should clean up on thread exit 32 | """ 33 | # Sanity check 34 | assert len(self.files) == 0 35 | # Thread cleanup class 36 | class ThreadedStats(mmstats.MmStats): 37 | # The behavior we're testing is in MmStats itself 38 | pass 39 | # Ensure we use {TID} 40 | s = ThreadedStats(filename='test-thread-cleanup-{PID}-{TID}.mmstats') 41 | # Threading 42 | ready = threading.Event() 43 | class WorkThread(threading.Thread): 44 | def run(self): 45 | # Do some work that touches our MmStats instance, 46 | # as a sanity check. 47 | assert s.filename 48 | ready.wait() 49 | threads = [WorkThread() for _ in range(100)] 50 | for t in threads: 51 | t.start() 52 | ready.set() # go! 53 | for t in threads: 54 | t.join() 55 | # Threads done - time to nuke 56 | s.remove() 57 | # Did they all die? 58 | assert len(self.files) == 0 59 | 60 | def test_tls(self): 61 | """MmStats instances are unique per thread""" 62 | class ScienceStats(mmstats.MmStats): 63 | facts = mmstats.StringField(size=50) 64 | 65 | stats = set() 66 | insts = {} 67 | 68 | s = ScienceStats(filename='test-tls-{TID}.mmstats') 69 | num_threads = 111 70 | ready = threading.Event() 71 | 72 | # Make it a mutable object (dict) instead of a bool so we can access it 73 | # inside the thread easily 74 | collision = {'status': False} 75 | 76 | class T(threading.Thread): 77 | def run(self): 78 | if s.filename in stats: 79 | collision['status'] = True 80 | else: 81 | stats.add(s.filename) 82 | 83 | # This is kind of silly, but would catch the case of a single 84 | # mmap being shared between threads 85 | insts[self.ident] = s.facts = str(uuid.uuid4()) 86 | 87 | # Wait for all threads to be started before completing 88 | # If we don't do this, thread.idents will be reused 89 | ready.wait() 90 | 91 | threads = [T() for _ in range(num_threads)] 92 | 93 | for t in threads: 94 | t.start() 95 | 96 | ready.set() # go! 97 | 98 | for t in threads: 99 | t.join() 100 | 101 | self.assertFalse(collision['status']) 102 | self.assertEqual(len(stats), num_threads) 103 | self.assertEqual(len(insts), num_threads) 104 | self.assertEqual(len(set(insts.values())), num_threads) 105 | 106 | def test_label_prefix(self): 107 | class StatsA(mmstats.MmStats): 108 | f2 = mmstats.UIntField(label='f.secondary') 109 | f1 = mmstats.UIntField() 110 | 111 | a = StatsA(filename='test-label-prefix1.mmstats') 112 | b = StatsA(filename='test-label-prefix2.mmstats', 113 | label_prefix='org.mmstats.') 114 | 115 | self.assertTrue('f1\x01\x00I' in a._mmap[:]) 116 | self.assertTrue('f.secondary\x01\x00I' in a._mmap[:]) 117 | self.assertTrue('org.mmstats.' not in a._mmap[:]) 118 | self.assertTrue('org.mmstats.f1\x01\x00I' in b._mmap[:]) 119 | self.assertTrue('org.mmstats.f.secondary\x01\x00I' in b._mmap[:]) 120 | 121 | # Attributes should be unaffected 122 | a.f1 = 2 123 | b.f1 = 3 124 | a.f2 = 4 125 | b.f2 = 5 126 | 127 | self.assertEqual(a.f1, 2) 128 | self.assertEqual(b.f1, 3) 129 | self.assertEqual(a.f2, 4) 130 | self.assertEqual(b.f2, 5) 131 | 132 | def test_mmap_resize1(self): 133 | class BigStats(mmstats.MmStats): 134 | f1 = mmstats.BoolField(label='f1'*(_mmap.PAGESIZE / 2)) 135 | f2 = mmstats.BoolField(label='f2'*(_mmap.PAGESIZE / 2)) 136 | 137 | bs = BigStats(filename='test-resize2.mmstats') 138 | self.assertEqual(bs.size, _mmap.PAGESIZE * 3) 139 | 140 | def test_mmap_resize2(self): 141 | class BigStats(mmstats.MmStats): 142 | f1 = mmstats.UIntField(label='f'+('o'*_mmap.PAGESIZE)) 143 | f2 = mmstats.UIntField(label='f'+('0'*_mmap.PAGESIZE)) 144 | f3 = mmstats.UIntField(label='f'+('1'*_mmap.PAGESIZE)) 145 | 146 | bs = BigStats(filename='test-resize2.mmstats') 147 | self.assertEqual(bs.size, _mmap.PAGESIZE * 4) 148 | self.assertEqual(bs.f1, 0) 149 | self.assertEqual(bs.f2, 0) 150 | self.assertEqual(bs.f3, 0) 151 | 152 | def test_subclassing(self): 153 | class ParentStats(mmstats.MmStats): 154 | a = mmstats.UIntField() 155 | b = mmstats.UIntField() 156 | 157 | class ChildAStats(ParentStats): 158 | a = mmstats.BoolField() 159 | c = mmstats.UIntField() 160 | 161 | class ChildBStats(ChildAStats): 162 | b = mmstats.BoolField() 163 | c = mmstats.BoolField() 164 | 165 | self.assertTrue(isinstance(ParentStats.a, mmstats.UIntField)) 166 | self.assertTrue(isinstance(ParentStats.b, mmstats.UIntField)) 167 | self.assertRaises(AttributeError, getattr, ParentStats, 'c') 168 | 169 | self.assertTrue(isinstance(ChildAStats.a, mmstats.BoolField)) 170 | self.assertTrue(isinstance(ChildAStats.b, mmstats.UIntField)) 171 | self.assertTrue(isinstance(ChildAStats.c, mmstats.UIntField)) 172 | 173 | self.assertTrue(isinstance(ChildBStats.a, mmstats.BoolField)) 174 | self.assertTrue(isinstance(ChildBStats.b, mmstats.BoolField)) 175 | self.assertTrue(isinstance(ChildBStats.c, mmstats.BoolField)) 176 | -------------------------------------------------------------------------------- /tests/test_naming.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | 4 | from mmstats import models, libgettid 5 | 6 | 7 | def test_defaults(): 8 | """Threadsafe defaults in expanded filename""" 9 | fn = models._expand_filename() 10 | assert str(os.getpid()) in fn, 'missing PID' 11 | assert str(libgettid.gettid()) in fn, 'missing TID' 12 | assert fn.endswith('.mmstats'), 'missing .mmstats extension' 13 | 14 | 15 | def test_substitutions(): 16 | fn = models._expand_filename(filename=' {CMD} {CMD} {PID} {TID}').split() 17 | cmd = os.path.basename(sys.argv[0]) 18 | assert fn[1] == cmd, fn[1] + ' != ' + cmd 19 | assert fn[1] == fn[2], 'unable to repeat substitutions' 20 | assert fn[3] == str(os.getpid()), 'PID wrong' 21 | assert fn[4] == str(libgettid.gettid()), 'TID wrong' 22 | -------------------------------------------------------------------------------- /tests/test_types.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | import struct 3 | import time 4 | import warnings 5 | 6 | from . import base 7 | 8 | import mmstats 9 | 10 | 11 | class TestTypes(base.MmstatsTestCase): 12 | def test_ints(self): 13 | class MyStats(mmstats.MmStats): 14 | zebras = mmstats.IntField() 15 | apples = mmstats.UIntField() 16 | oranges = mmstats.UIntField() 17 | 18 | mmst = MyStats(filename='test-ints.mmstats') 19 | 20 | # Basic format 21 | self.assertEqual(mmst._mmap[0], '\x01') 22 | self.assertTrue('apples\x01\x00I' in mmst._mmap.raw) 23 | self.assertTrue('oranges\x01\x00I' in mmst._mmap.raw) 24 | self.assertTrue('zebras\x01\x00i' in mmst._mmap.raw) 25 | 26 | # Stat manipulation 27 | self.assertEqual(mmst.apples, 0) 28 | self.assertEqual(mmst.oranges, 0) 29 | self.assertEqual(mmst.zebras, 0) 30 | 31 | mmst.apples = 1 32 | self.assertEqual(mmst.apples, 1) 33 | self.assertEqual(mmst.oranges, 0) 34 | self.assertEqual(mmst.zebras, 0) 35 | 36 | mmst.zebras = -9001 37 | self.assertEqual(mmst.apples, 1) 38 | self.assertEqual(mmst.oranges, 0) 39 | self.assertEqual(mmst.zebras, -9001) 40 | 41 | mmst.apples = -100 42 | self.assertEqual(mmst.apples, (2**32)-100) 43 | 44 | def test_shorts(self): 45 | class ShortFields(mmstats.MmStats): 46 | a = mmstats.ShortField() 47 | b = mmstats.UShortField() 48 | 49 | s = ShortFields(filename='test-shorts.mmstats') 50 | self.assertEqual(s.a, 0, s.a) 51 | self.assertEqual(s.b, 0, s.b) 52 | s.a = -1 53 | self.assertEqual(s.a, -1, s.a) 54 | self.assertEqual(s.b, 0, s.b) 55 | s.b = (2**16)-1 56 | self.assertEqual(s.a, -1, s.a) 57 | self.assertEqual(s.b, (2**16)-1, s.b) 58 | s.b = -2 59 | self.assertEqual(s.a, -1, s.a) 60 | self.assertEqual(s.b, (2**16)-2, s.b) 61 | 62 | def test_bools(self): 63 | class BoolFields(mmstats.MmStats): 64 | a = mmstats.BoolField() 65 | b = mmstats.BoolField(initial=True) 66 | 67 | s = BoolFields(filename='test-bools.mmstats') 68 | self.assertTrue('a\x01\x00?\xff\x00' in s._mmap[:], repr(s._mmap[:30])) 69 | self.assertTrue('b\x01\x00?\xff\x01' in s._mmap[:], repr(s._mmap[:30])) 70 | self.assertTrue(s.a is False, s.a) 71 | self.assertTrue(s.b is True, s.b) 72 | s.a = 'Anything truthy at all' 73 | self.assertTrue(s.a is True, s.a) 74 | self.assertTrue(s.b is True, s.b) 75 | s.a = [] # Anything falsey 76 | self.assertTrue(s.a is False, s.a) 77 | self.assertTrue(s.b is True, s.b) 78 | s.b = False 79 | s.a = s.b 80 | self.assertTrue(s.a is False, s.a) 81 | self.assertTrue(s.b is False, s.b) 82 | 83 | def test_mixed(self): 84 | class MixedStats(mmstats.MmStats): 85 | a = mmstats.UIntField() 86 | b = mmstats.BoolField() 87 | c = mmstats.IntField() 88 | d = mmstats.BoolField(label='The Bool') 89 | e = mmstats.ShortField(label='shortie') 90 | 91 | m1 = MixedStats(label_prefix='m1::', filename='test-m1.mmstats') 92 | m2 = MixedStats(label_prefix='m2::', filename='test-m2.mmstats') 93 | 94 | self.assertTrue('m2::shortie' not in m1._mmap[:]) 95 | self.assertTrue('m2::shortie' in m2._mmap[:], repr(m2._mmap[:40])) 96 | 97 | for i in range(10): 98 | m1.a = i 99 | m2.a = i * 2 100 | m1.b = True 101 | m2.b = False 102 | m1.c = -i 103 | m2.c = -i * 2 104 | m1.d = False 105 | m2.d = True 106 | m1.e = 1 107 | m2.e = i * 10 108 | 109 | self.assertEqual(m1.a, i, m1.a) 110 | self.assertEqual(m2.a, i * 2, m2.a) 111 | self.assertTrue(m1.b is True, m1.b) 112 | self.assertTrue(m2.b is False, m2.b) 113 | self.assertEqual(m1.c, -i, m1.c) 114 | self.assertEqual(m2.c, -i * 2, m2.c) 115 | self.assertTrue(m1.d is False, m1.d) 116 | self.assertTrue(m2.d is True, m2.d) 117 | self.assertEqual(m1.e, 1, m1.e) 118 | self.assertEqual(m2.e, 90, m2.e) 119 | 120 | def test_counter_sz(self): 121 | self.assertEquals(ctypes.sizeof(mmstats.CounterField.buffer_type), 8) 122 | self.assertEquals( 123 | struct.calcsize(mmstats.CounterField.type_signature), 8) 124 | 125 | def test_counter(self): 126 | """Test counter field""" 127 | # Make sure this test only hits non-deprecated APIs 128 | warnings.filterwarnings('error', category=DeprecationWarning) 129 | class SimpleCounter(mmstats.MmStats): 130 | counter = mmstats.CounterField() 131 | 132 | s = SimpleCounter(filename='test_counter.mmstats') 133 | self.assertEqual(s.counter.value, 0) 134 | s.counter.incr() 135 | self.assertEqual(s.counter.value, 1) 136 | s.counter.incr() 137 | self.assertEqual(s.counter.value, 2) 138 | s.counter.incr(amount=8) 139 | self.assertEqual(s.counter.value, 10) 140 | s.counter.incr(-11) 141 | self.assertNotEqual(s.counter.value, -1) 142 | self.assertNotEqual(s.counter.value, 0) 143 | s.counter.value = 0 144 | self.assertEqual(s.counter.value, 0) 145 | 146 | def test_deprecated_inc(self): 147 | class SimpleCounter(mmstats.MmStats): 148 | counter = mmstats.CounterField() 149 | 150 | s = SimpleCounter(filename='test-deprecated_inc.mmstats') 151 | self.assertEqual(s.counter.value, 0) 152 | 153 | # Make sure the warning is in place 154 | warnings.filterwarnings('error', category=DeprecationWarning) 155 | self.assertRaises(DeprecationWarning, s.counter.inc) 156 | self.assertEqual(s.counter.value, 0) 157 | 158 | # Make sure that the function still works despite being deprecated 159 | warnings.filterwarnings('ignore', category=DeprecationWarning) 160 | s.counter.inc() 161 | self.assertEqual(s.counter.value, 1) 162 | s.counter.inc(n=99) 163 | self.assertEqual(s.counter.value, 100) 164 | 165 | def test_floats(self): 166 | class FloatTest(mmstats.MmStats): 167 | f = mmstats.FloatField() 168 | d = mmstats.DoubleField() 169 | 170 | ft = FloatTest(filename='test_floats.mmstats') 171 | self.assertEqual(ft.f, 0.0) 172 | self.assertEqual(ft.d, 0.0) 173 | ft.d = ft.f = 1.0 174 | self.assertEqual(ft.f, 1.0) 175 | self.assertEqual(ft.d, 1.0) 176 | ft.d = ft.f = -1.0 177 | self.assertEqual(ft.f, -1.0) 178 | self.assertEqual(ft.d, -1.0) 179 | ft.d = ft.f = 1.0 / 3 180 | self.assertTrue(ft.f > 0.3) 181 | self.assertTrue(ft.d > 0.3) 182 | self.assertTrue(ft.f < 0.4) 183 | self.assertTrue(ft.d < 0.4) 184 | 185 | def test_average(self): 186 | class AvgTest(mmstats.MmStats): 187 | avg = mmstats.AverageField() 188 | at = AvgTest(filename='test_average.mmstats') 189 | self.assertEqual(at.avg.value, 0.0) 190 | at.avg.add(1) 191 | self.assertEqual(at.avg.value, 1.0) 192 | at.avg.add(1) 193 | self.assertEqual(at.avg.value, 1.0) 194 | at.avg.add(1) 195 | self.assertEqual(at.avg.value, 1.0) 196 | at.avg.add(-3) 197 | self.assertEqual(at.avg.value, 0.0) 198 | at.avg.add(1) 199 | self.assertTrue(0 < at.avg.value < 1) 200 | 201 | def test_static_strings(self): 202 | class StaticStringStats(mmstats.BaseMmStats): 203 | a = mmstats.StaticTextField(label="text", value="something cool") 204 | m1 = StaticStringStats(filename='test_strings_simple.mmstats') 205 | 206 | self.assertTrue(m1.a, 'something cool') 207 | 208 | def test_strings(self): 209 | class StrTest(mmstats.MmStats): 210 | f = mmstats.FloatField() 211 | s = mmstats.StringField(10) 212 | c = mmstats.CounterField() 213 | st = StrTest(filename='test_strings.mmstats') 214 | self.assertEqual(st.f, 0.0) 215 | self.assertEqual(st.c.value, 0) 216 | self.assertEqual(st.s, '') 217 | st.s = 'a' * 11 218 | self.assertEqual(st.s, 'a' * 10) 219 | st.s = 'b' 220 | self.assertEqual(st.s, 'b') 221 | self.assertEqual(st.f, 0.0) 222 | self.assertEqual(st.c.value, 0) 223 | st.f = 1.0 224 | st.c.inc() 225 | self.assertEqual(st.s, 'b') 226 | self.assertEqual(st.f, 1.0) 227 | self.assertEqual(st.c.value, 1) 228 | st.s = u'\u2764' * 11 229 | # character is multibyte, so only 3 fit in 10 UTF8 encoded bytes 230 | self.assertEqual(st.s, u'\u2764' * 3) 231 | self.assertEqual(st.f, 1.0) 232 | self.assertEqual(st.c.value, 1) 233 | 234 | def test_moving_avg(self): 235 | class MATest(mmstats.MmStats): 236 | m1 = mmstats.MovingAverageField() 237 | a = mmstats.AverageField() 238 | m2 = mmstats.MovingAverageField() 239 | stats = MATest(filename='test_moving_avg.mmstats') 240 | self.assertEqual(stats.m1.value, 0.0) 241 | stats.m1.add(1) 242 | self.assertEqual(stats.m1.value, 1.0) 243 | stats.m1.add(2) 244 | self.assertEqual(stats.m1.value, 1.5) 245 | for i in range(1000): 246 | stats.m1.add(1) 247 | stats.a.add(i) 248 | stats.m2.add(i) 249 | self.assertEqual(stats.m1.value, 1.0) 250 | self.assertTrue(stats.a.value < stats.m2.value, 251 | '%d < %d' % (stats.a.value, stats.m2.value)) 252 | 253 | def test_moving_avg_alt_sizes(self): 254 | class MATest2(mmstats.MmStats): 255 | m1 = mmstats.MovingAverageField(size=1) 256 | m2 = mmstats.MovingAverageField() 257 | m3 = mmstats.MovingAverageField(size=1000) 258 | stats = MATest2(filename='test_moving_avg_alt_sizes.mmstats') 259 | for i in range(1000): 260 | stats.m1.add(i) 261 | stats.m2.add(i) 262 | stats.m3.add(i) 263 | self.assertEqual(stats.m1.value, 999.0) 264 | self.assertTrue(stats.m1.value > stats.m2.value > stats.m3.value) 265 | for i in range(1000): 266 | stats.m1.add(i) 267 | stats.m2.add(i) 268 | stats.m3.add(i) 269 | self.assertEqual(stats.m1.value, 999.0) 270 | self.assertTrue(stats.m1.value > stats.m2.value > stats.m3.value) 271 | 272 | def test_timer(self): 273 | class TTest(mmstats.MmStats): 274 | m1 = mmstats.MovingAverageField() 275 | t1 = mmstats.TimerField() 276 | c = mmstats.CounterField() 277 | t2 = mmstats.TimerField(timer=time.clock) 278 | stats = TTest(filename='test_timer.mmstats') 279 | with stats.t1 as timer: 280 | # Timer's value should == 0 until this context exits 281 | self.assertEqual(stats.t1.value, 0.0) 282 | self.assertEqual(stats.t2.value, 0.0) 283 | self.assertEqual(stats.t2.last, 0.0) 284 | # Some time has passed 285 | self.assertTrue(timer.elapsed > 0.0) 286 | e = timer.elapsed 287 | # Any later elapsed check should be > than the former 288 | time.sleep(0.001) 289 | self.assertTrue(timer.elapsed > e) 290 | self.assertNotEqual(stats.t1.value, stats.t2.value) 291 | self.assertEqual(stats.t1.value, stats.t1.last) 292 | oldval = stats.t1.value 293 | last = stats.t1.last 294 | stats.t1.start() 295 | stats.t1.stop() 296 | self.assertTrue(stats.t1.last < last) 297 | self.assertTrue(stats.t1.value < oldval) 298 | --------------------------------------------------------------------------------