├── Dockerfile ├── Dockerfile-dev ├── LICENSE ├── PrometheusUserMonitoringArchitecture.png ├── README.md ├── SweetSlackOps.png ├── clientSrc └── aggregatorClient.js ├── config ├── .babelrc └── metricConfigs │ ├── appMetricConfig.json │ └── performanceTimingMetricConfig.json ├── demo ├── grafanaConfig │ ├── .gitignore │ └── grafana.db ├── prometheusConfig │ └── prometheus.yml └── sampleApp │ └── index.html ├── docker-compose.yaml ├── navigationtiming.png ├── runDevServer.sh ├── serverPackage.json └── serverSrc ├── .flowconfig ├── __tests__ └── reportingTests.js ├── aggregators ├── __tests__ │ ├── counterTest.js │ └── histogramTest.js ├── counter.js ├── histogram.js └── util.js ├── config.js ├── makeMetricsAggregator.js ├── readMetricConfigs.js └── server.js /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:6 2 | 3 | RUN apt-get update && apt-get install -y libelf-dev python-all libicu-dev 4 | RUN node --version 5 | RUN npm --version 6 | 7 | RUN npm install -g babel-cli 8 | RUN npm install -g babel-watch 9 | RUN npm install -g babel-core 10 | RUN npm install -g babel-loader 11 | RUN npm install -g babel-register 12 | 13 | WORKDIR /stage 14 | 15 | RUN npm install babel-plugin-syntax-async-functions 16 | RUN npm install babel-plugin-transform-builtin-extend 17 | RUN npm install babel-plugin-transform-flow-strip-types 18 | RUN npm install babel-plugin-transform-object-rest-spread 19 | RUN npm install babel-plugin-transform-regenerator 20 | RUN npm install babel-preset-es2015 21 | 22 | COPY ./config/.babelrc /stage/.babelrc 23 | 24 | 25 | COPY ./serverPackage.json /stage/package.json 26 | 27 | RUN npm install 28 | 29 | RUN mkdir /stage/static 30 | RUN mkdir /stage/built 31 | 32 | # Build the server and put it in /stage/built 33 | COPY ./serverSrc /stage/serverSrc 34 | RUN babel --out-dir /stage/built /stage/serverSrc 35 | 36 | # Build the client lib and put it in /stage/static 37 | COPY ./clientSrc /stage/clientSrc 38 | RUN babel --out-file /stage/static/aggregatorClient.js /stage/clientSrc/aggregatorClient.js 39 | 40 | WORKDIR /stage/built 41 | CMD ["node", "server.js"] -------------------------------------------------------------------------------- /Dockerfile-dev: -------------------------------------------------------------------------------- 1 | FROM node:6 2 | 3 | RUN apt-get update && apt-get install -y libelf-dev python-all libicu-dev 4 | RUN node --version 5 | RUN npm --version 6 | 7 | RUN npm install -g babel-cli 8 | RUN npm install -g babel-watch 9 | RUN npm install -g babel-core 10 | RUN npm install -g babel-loader 11 | RUN npm install -g babel-register 12 | RUN npm install -g jest 13 | 14 | WORKDIR /stage 15 | 16 | RUN npm install babel-plugin-syntax-async-functions 17 | RUN npm install babel-plugin-transform-builtin-extend 18 | RUN npm install babel-plugin-transform-flow-strip-types 19 | RUN npm install babel-plugin-transform-object-rest-spread 20 | RUN npm install babel-plugin-transform-regenerator 21 | RUN npm install babel-preset-es2015 22 | 23 | RUN npm install jest-cli babel-jest 24 | 25 | COPY ./config/.babelrc /stage/.babelrc 26 | 27 | 28 | COPY ./serverPackage.json /stage/package.json 29 | 30 | RUN npm install 31 | 32 | RUN mkdir /stage/static 33 | 34 | COPY ./runDevServer.sh /stage/runDevServer.sh 35 | 36 | # At this point /stage is set up with serverPackage.json as package.json 37 | # and all node_modules installed. 38 | # 39 | # Add your own command in docker-compose.yaml, e.g.: 40 | # 1. mount source into /stage/src 41 | # 2. run `babel-watch src/server.js` or 2. run jest --watch 42 | 43 | RUN npm install -g flow-bin@0.40.0 -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /PrometheusUserMonitoringArchitecture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peardeck/prometheus-user-metrics/3fda55db01d9f297d1a9995ce6ab3535d450b35e/PrometheusUserMonitoringArchitecture.png -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # User Monitoring for Prometheus 2 | 3 | Prometheus, a [Cloud Native Computing Foundation](https://cncf.io/) project, is a systems and service monitoring system. *This* project provides the infrastructure you need to do end-user monitoring in Prometheus as well. 4 | 5 | ## Designed for use cases like: 6 | 7 | * Set alarms for spikes in page load times or error rates! 8 | * Measure real experienced latencies for API calls! 9 | * You don't control Firebase (insert your favorite third-party "serverless" thing here) but now you can monitor how your users are experiencing it! 10 | * Understand how much usage a newly-deployed feature is getting! 11 | * Use alarms as end-to-end tests by getting a slack message when a usage pattern changes dramatically! Automatically warn yourselves if your usage drops from last week - either overall or for a particular feature! 12 | * No need for third-party services that compromise your users' privacy or security! 13 | * Easy to set up and cheap to run! 14 | 15 | ## Try it locally! 16 | 17 | 1. Clone repo 18 | 2. `docker-compose up` 19 | 3. Browse to http://localhost:8080 20 | 21 | ## Pictures You Can Use to Impress Your Friends 22 | 23 | Github's Frontend Response Time Graph is a snap! We can literally generate this graph for you AND let you set alarms on it without any manual instrumentation on your part. See https://githubengineering.com/browser-monitoring-for-github-com/ for how Github uses these metrics. 24 | 25 | ![Github's Frontend Response Time Graph](https://cloud.githubusercontent.com/assets/187987/7738101/d9892654-ff05-11e4-8d62-340091dada79.png) 26 | 27 | Here's how the demo for this project loads the same graph: 28 | ![The graph from this project](/navigationtiming.png?raw=true) 29 | 30 | Wow, your super-cool Slack-ops channel can be even more glib about outages... NOW FOR THE END USER! 31 | ![Slack Ops](/SweetSlackOps.png?raw=true "Your users can't get their S3 photos, but your monitoring is pretty cool!") 32 | 33 | You don't control Firebase (insert your third-party "serverless" thing here) but now you can monitor how your users are experiencing it! 34 | 35 | ## How it works 36 | 37 | The challenge in monitoring your real users' experiences is that Prometheus can't scrape their clients, so this project adds a service that Prometheus CAN scrape, and provides an API that your clients can PUSH their metrics too. We provide client-side libraries to make that a snap. 38 | 39 | ![Prometheus User Monitoring Architecture Diagram](/PrometheusUserMonitoringArchitecture.png?raw=true "Prometheus User Monitoring Architecture") 40 | 41 | ## How to use it 42 | 43 | ### Server-side 44 | 45 | 1. Put the aggregator in your cloud. Prometheus will notice it automatically by its annotations! 46 | `kubectl apply -f prometheus-user-monitoring-aggregator.yaml` 47 | 48 | 2. Make a route through your gateway so clients can reach the aggregator. For testing it out, this could just be 49 | `kubectl port-forward $(kubectl get pod -l app=prometheus-user-monitoring-aggregator -o=jsonpath={.items[*].metadata.name}) 3000` 50 | 51 | ### Client-side (JS) 52 | 53 | 1. EZ-setup: just add this snippet to your HTML: 54 | 55 | ``` 56 | // copied from Google Analytics Snippet, adapted for Prometheus Aggregator 57 | (function(i,s,o,g,r,a,m){i['PrometheusAggregatorObjectName']=r;i[r]=i[r]||function(){ 58 | (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), 59 | m=s.getElementsByTagName(o)[0];a.async=1;a.src=(g+'/static/aggregatorClient.js');m.parentNode.insertBefore(a,m); 60 | i[r].aggregatorServerRoot = g; 61 | })(window,document,'script','http://localhost:3000','prometheusAggregator'); 62 | ``` 63 | 64 | 65 | That's it! It's already collecting enough metrics to do github's user monitoring in the Sweet Graph above. If you want to collect custom metrics, then you'd need to add them to a whitelist. Once you have that set up (it's just a [config file](/config/metricConfigs/appMetricConfig.json)), then you can monitor metrics like: 66 | 67 | 1. How much does this page get loaded? 68 | ``` 69 | prometheusAggregator('increment', 'app_load_succeeded', { app: 'whateverAppId'}, 1); 70 | ``` 71 | 72 | 2. How many users are using the new feature we launched? 73 | ``` 74 | featureButton.on('click', () => { 75 | doFeatureX(); 76 | prometheusAggregator('increment', 'feature_usage_total', { feature: 'whateverFeatureName'}, 1); 77 | }); 78 | ``` 79 | 80 | 3. TODO: What's the average latency to a third-party service like firebase? 81 | ``` 82 | prometheusAggregator('observe', 'firebase_latency', { firebaseHost: 'whatever.firebaseio.com' }, measuredLatency) 83 | ``` 84 | 85 | The client aggregates all the metrics and sends them to the aggregator at an interval of X seconds. The aggregator automatically gains some notion of how many clients are connected with `rate(clientSamples) / X` 86 | 87 | ## The Future of this Project 88 | 89 | We use this in production at Pear Deck and it's pretty great. We don't know how widely applicable it is. Let us know by leaving an issue or starring the project! You can also email us at hello@peardeck.com. -------------------------------------------------------------------------------- /SweetSlackOps.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peardeck/prometheus-user-metrics/3fda55db01d9f297d1a9995ce6ab3535d450b35e/SweetSlackOps.png -------------------------------------------------------------------------------- /clientSrc/aggregatorClient.js: -------------------------------------------------------------------------------- 1 | /* 2 | (c) 2017 Pear Deck, Inc. 3 | License: Apache 2 4 | */ 5 | 6 | (function () { 7 | function post(url, data) { 8 | var req = new XMLHttpRequest(); 9 | req.open("POST", url, true); 10 | req.setRequestHeader('Content-type', 'application/json'); 11 | 12 | req.onreadystatechange = function () { 13 | if (req.readyState === 4 && req.status == 200) { 14 | // :tada: 15 | } else { 16 | // if a send doesn't succeed, we lose the metrics, but we probably don't want to bother anyone w/ the details. 17 | } 18 | }; 19 | 20 | req.send(data); 21 | } 22 | 23 | function setUpAndStartInterval({ aggregatorReportingUrl }) { 24 | let counterIncrements = {}; 25 | let histogramObservations = {}; 26 | 27 | setInterval(sendUpdates, 10000); 28 | 29 | function sendUpdates() { 30 | const body = JSON.stringify(packageUpdates()); 31 | 32 | post(aggregatorReportingUrl, body); 33 | 34 | // clear all metrics. If the most recent send does not succeed, then 35 | // we will lose that batch of metrics. :shrug: 36 | counterIncrements = {}; 37 | histogramObservations = {}; 38 | } 39 | 40 | function packageUpdates() { 41 | const counterUpdates = Object.values(counterIncrements); 42 | const histogramUpdates = Object.values(histogramObservations); 43 | 44 | return [ 45 | ...counterUpdates, 46 | ...histogramUpdates 47 | ]; 48 | } 49 | 50 | function increment(name, labels, inc) { 51 | const key = `${name}{${flattenLabels(labels)}}`; 52 | if (counterIncrements[key]) { 53 | counterIncrements[key].inc += inc; 54 | } else { 55 | counterIncrements[key] = { 56 | metricName: name, 57 | metricType: 'counter', 58 | labels, 59 | inc: inc, 60 | }; 61 | } 62 | } 63 | 64 | function observe(name, labels, observation) { 65 | const key = `${name}{${flattenLabels(labels)}}`; 66 | if (histogramObservations[key]) { 67 | histogramObservations[key].observations.push(observation); 68 | } else { 69 | histogramObservations[key] = { 70 | metricName: name, 71 | metricType: 'histogram', 72 | labels, 73 | observations: [observation] 74 | }; 75 | } 76 | } 77 | 78 | function flattenLabels(labelsObject) { 79 | const keys = Object.keys(labelsObject).sort(); 80 | const printed = keys.map((key) => `${key}="${labelsObject[key]}"`); 81 | return printed.join(','); 82 | } 83 | 84 | return function (fnName, metricName, labels, value) { 85 | if (fnName === 'increment') { 86 | increment(metricName, labels, value); 87 | } else if (fnName === 'observe') { 88 | observe(metricName, labels, value); 89 | } else { 90 | console.warn("unknown fn name ", fnName); 91 | } 92 | }; 93 | } 94 | 95 | function reportNavigationTiming() { 96 | if (!performance || !performance.timing) { 97 | console.log("performance.timing not supported"); 98 | return; 99 | } 100 | 101 | var navigationStart = performance.timing.navigationStart; 102 | const prometheusAggregator = window[window['PrometheusAggregatorObjectName']]; 103 | var key; 104 | for (key in performance.timing) { 105 | if (typeof performance.timing[key] === 'number' && performance.timing[key] > 0) { 106 | prometheusAggregator('observe', 'performance_timing_' + key, {}, (performance.timing[key] - navigationStart) / 1000.0); 107 | } 108 | } 109 | } 110 | 111 | const { q, aggregatorServerRoot } = window[window['PrometheusAggregatorObjectName']]; 112 | 113 | const actualFunction = window[window['PrometheusAggregatorObjectName']] = setUpAndStartInterval({ aggregatorReportingUrl: aggregatorServerRoot + '/record' }); 114 | 115 | (q || []).forEach((args) => actualFunction(...args)); 116 | 117 | reportNavigationTiming(); 118 | }()); -------------------------------------------------------------------------------- /config/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ "es2015" ], 3 | "plugins": [ 4 | "transform-object-rest-spread", 5 | "syntax-async-functions", 6 | "transform-regenerator", 7 | "babel-plugin-transform-flow-strip-types", 8 | ["babel-plugin-transform-builtin-extend", { 9 | "globals": ["Error", "Array"] 10 | }] 11 | ] 12 | } -------------------------------------------------------------------------------- /config/metricConfigs/appMetricConfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "allowedMetrics": [ 3 | { 4 | "name": "app_load_succeeded", 5 | "help": "succesful app loads", 6 | "type": "counter", 7 | "labels": [ 8 | { 9 | "name": "app", 10 | "allowedValues": [ 11 | "student", 12 | "teacher", 13 | "editor", 14 | "home", 15 | "join" 16 | ] 17 | } 18 | ] 19 | }, 20 | { 21 | "name": "usage_total", 22 | "help": "counts of usage, like times a feature has been used, etc", 23 | "type": "counter", 24 | "labels": [ 25 | { 26 | "name": "browser", 27 | "allowedValues": [ 28 | "chrome", 29 | "firefox", 30 | "safari", 31 | "edge" 32 | ] 33 | }, 34 | { 35 | "name": "feature", 36 | "allowedValues": [ 37 | "quickQuestion", 38 | "selfPacedMode", 39 | "blockStudent", 40 | "showContent" 41 | ] 42 | } 43 | ] 44 | }, 45 | { 46 | "name": "firebase_response_time", 47 | "help": "measures firebase response times in seconds", 48 | "type": "histogram", 49 | "labels": [ 50 | { 51 | "name": "firebaseHost", 52 | "allowedValues": [ 53 | "pd-dev-1.firebaseio.com", 54 | "pd-dev-2.firebaseio.com" 55 | ] 56 | } 57 | ], 58 | "buckets": [ 59 | 0.05, 60 | 0.1, 61 | 0.2, 62 | 0.5, 63 | 1, 64 | 2, 65 | 5, 66 | 10, 67 | 20, 68 | 50, 69 | 100 70 | ] 71 | } 72 | ] 73 | } -------------------------------------------------------------------------------- /config/metricConfigs/performanceTimingMetricConfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "allowedMetrics": [ 3 | { 4 | "name": "performance_timing_navigationStart", 5 | "help": "Performance timing metric", 6 | "type": "histogram", 7 | "labels": [], 8 | "buckets": [ 9 | 0.01, 10 | 0.05, 11 | 0.1, 12 | 0.2, 13 | 0.5, 14 | 1, 15 | 1.2, 16 | 1.5, 17 | 2, 18 | 5, 19 | 10 20 | ] 21 | }, 22 | { 23 | "name": "performance_timing_unloadEventStart", 24 | "help": "Performance timing metric", 25 | "type": "histogram", 26 | "labels": [], 27 | "buckets": [ 28 | 0.01, 29 | 0.05, 30 | 0.1, 31 | 0.2, 32 | 0.5, 33 | 1, 34 | 1.2, 35 | 1.5, 36 | 2, 37 | 5, 38 | 10 39 | ] 40 | }, 41 | { 42 | "name": "performance_timing_unloadEventEnd", 43 | "help": "Performance timing metric", 44 | "type": "histogram", 45 | "labels": [], 46 | "buckets": [ 47 | 0.01, 48 | 0.05, 49 | 0.1, 50 | 0.2, 51 | 0.5, 52 | 1, 53 | 1.2, 54 | 1.5, 55 | 2, 56 | 5, 57 | 10 58 | ] 59 | }, 60 | { 61 | "name": "performance_timing_fetchStart", 62 | "help": "Performance timing metric", 63 | "type": "histogram", 64 | "labels": [], 65 | "buckets": [ 66 | 0.01, 67 | 0.05, 68 | 0.1, 69 | 0.2, 70 | 0.5, 71 | 1, 72 | 1.2, 73 | 1.5, 74 | 2, 75 | 5, 76 | 10 77 | ] 78 | }, 79 | { 80 | "name": "performance_timing_domainLookupStart", 81 | "help": "Performance timing metric", 82 | "type": "histogram", 83 | "labels": [], 84 | "buckets": [ 85 | 0.01, 86 | 0.05, 87 | 0.1, 88 | 0.2, 89 | 0.5, 90 | 1, 91 | 1.2, 92 | 1.5, 93 | 2, 94 | 5, 95 | 10 96 | ] 97 | }, 98 | { 99 | "name": "performance_timing_domainLookupEnd", 100 | "help": "Performance timing metric", 101 | "type": "histogram", 102 | "labels": [], 103 | "buckets": [ 104 | 0.01, 105 | 0.05, 106 | 0.1, 107 | 0.2, 108 | 0.5, 109 | 1, 110 | 1.2, 111 | 1.5, 112 | 2, 113 | 5, 114 | 10 115 | ] 116 | }, 117 | { 118 | "name": "performance_timing_connectStart", 119 | "help": "Performance timing metric", 120 | "type": "histogram", 121 | "labels": [], 122 | "buckets": [ 123 | 0.01, 124 | 0.05, 125 | 0.1, 126 | 0.2, 127 | 0.5, 128 | 1, 129 | 1.2, 130 | 1.5, 131 | 2, 132 | 5, 133 | 10 134 | ] 135 | }, 136 | { 137 | "name": "performance_timing_connectEnd", 138 | "help": "Performance timing metric", 139 | "type": "histogram", 140 | "labels": [], 141 | "buckets": [ 142 | 0.01, 143 | 0.05, 144 | 0.1, 145 | 0.2, 146 | 0.5, 147 | 1, 148 | 1.2, 149 | 1.5, 150 | 2, 151 | 5, 152 | 10 153 | ] 154 | }, 155 | { 156 | "name": "performance_timing_requestStart", 157 | "help": "Performance timing metric", 158 | "type": "histogram", 159 | "labels": [], 160 | "buckets": [ 161 | 0.01, 162 | 0.05, 163 | 0.1, 164 | 0.2, 165 | 0.5, 166 | 1, 167 | 1.2, 168 | 1.5, 169 | 2, 170 | 5, 171 | 10 172 | ] 173 | }, 174 | { 175 | "name": "performance_timing_responseStart", 176 | "help": "Performance timing metric", 177 | "type": "histogram", 178 | "labels": [], 179 | "buckets": [ 180 | 0.01, 181 | 0.05, 182 | 0.1, 183 | 0.2, 184 | 0.5, 185 | 1, 186 | 1.2, 187 | 1.5, 188 | 2, 189 | 5, 190 | 10 191 | ] 192 | }, 193 | { 194 | "name": "performance_timing_responseEnd", 195 | "help": "Performance timing metric", 196 | "type": "histogram", 197 | "labels": [], 198 | "buckets": [ 199 | 0.01, 200 | 0.05, 201 | 0.1, 202 | 0.2, 203 | 0.5, 204 | 1, 205 | 1.2, 206 | 1.5, 207 | 2, 208 | 5, 209 | 10 210 | ] 211 | }, 212 | { 213 | "name": "performance_timing_domLoading", 214 | "help": "Performance timing metric", 215 | "type": "histogram", 216 | "labels": [], 217 | "buckets": [ 218 | 0.01, 219 | 0.05, 220 | 0.1, 221 | 0.2, 222 | 0.5, 223 | 1, 224 | 1.2, 225 | 1.5, 226 | 2, 227 | 5, 228 | 10 229 | ] 230 | }, 231 | { 232 | "name": "performance_timing_domInteractive", 233 | "help": "Performance timing metric", 234 | "type": "histogram", 235 | "labels": [], 236 | "buckets": [ 237 | 0.01, 238 | 0.05, 239 | 0.1, 240 | 0.2, 241 | 0.5, 242 | 1, 243 | 1.2, 244 | 1.5, 245 | 2, 246 | 5, 247 | 10 248 | ] 249 | }, 250 | { 251 | "name": "performance_timing_domContentLoadedEventStart", 252 | "help": "Performance timing metric", 253 | "type": "histogram", 254 | "labels": [], 255 | "buckets": [ 256 | 0.01, 257 | 0.05, 258 | 0.1, 259 | 0.2, 260 | 0.5, 261 | 1, 262 | 1.2, 263 | 1.5, 264 | 2, 265 | 5, 266 | 10 267 | ] 268 | }, 269 | { 270 | "name": "performance_timing_domContentLoadedEventEnd", 271 | "help": "Performance timing metric", 272 | "type": "histogram", 273 | "labels": [], 274 | "buckets": [ 275 | 0.01, 276 | 0.05, 277 | 0.1, 278 | 0.2, 279 | 0.5, 280 | 1, 281 | 1.2, 282 | 1.5, 283 | 2, 284 | 5, 285 | 10 286 | ] 287 | }, 288 | { 289 | "name": "performance_timing_domComplete", 290 | "help": "Performance timing metric", 291 | "type": "histogram", 292 | "labels": [], 293 | "buckets": [ 294 | 0.01, 295 | 0.05, 296 | 0.1, 297 | 0.2, 298 | 0.5, 299 | 1, 300 | 1.2, 301 | 1.5, 302 | 2, 303 | 5, 304 | 10 305 | ] 306 | }, 307 | { 308 | "name": "performance_timing_loadEventStart", 309 | "help": "Performance timing metric", 310 | "type": "histogram", 311 | "labels": [], 312 | "buckets": [ 313 | 0.01, 314 | 0.05, 315 | 0.1, 316 | 0.2, 317 | 0.5, 318 | 1, 319 | 1.2, 320 | 1.5, 321 | 2, 322 | 5, 323 | 10 324 | ] 325 | } 326 | ] 327 | } -------------------------------------------------------------------------------- /demo/grafanaConfig/.gitignore: -------------------------------------------------------------------------------- 1 | sessions -------------------------------------------------------------------------------- /demo/grafanaConfig/grafana.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peardeck/prometheus-user-metrics/3fda55db01d9f297d1a9995ce6ab3535d450b35e/demo/grafanaConfig/grafana.db -------------------------------------------------------------------------------- /demo/prometheusConfig/prometheus.yml: -------------------------------------------------------------------------------- 1 | global: 2 | scrape_interval: 15s 3 | evaluation_interval: 15s 4 | 5 | # rule_files: 6 | # - /etc/config/rules 7 | # - /etc/config/alerts 8 | 9 | scrape_configs: 10 | - job_name: metrics-aggregator 11 | static_configs: 12 | - targets: 13 | - metrics-aggregator-dev-server:9102 -------------------------------------------------------------------------------- /demo/sampleApp/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 16 | 17 | 18 | 19 |

Super-simple demo (open in multiple tabs)

20 |

This page is an example client that you might have. The dashboard below is an iframe of what you would have privately in your k8s cluster.

21 |
    22 |
  1. Simulate some client-side behavior 23 |

    24 | 25 | 26 | 27 | 28 |

    29 |

    30 | (or just refresh this page a bunch. Make sure you wait 10s for stats to be recorded before refreshing again). 31 |

  2. 32 |
  3. You should see activity show up below in under 30s.

  4. 33 |
  5. Let us know what you think at https://github.com/peardeck/prometheus-user-metrics

  6. 34 |
35 | 36 | 37 | 38 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /docker-compose.yaml: -------------------------------------------------------------------------------- 1 | version: "2" 2 | services: 3 | dev-server: 4 | build: 5 | context: . 6 | dockerfile: Dockerfile-dev 7 | command: 8 | - bash 9 | - runDevServer.sh 10 | ports: 11 | - 3000:3000 12 | - 9102:9102 13 | environment: 14 | PUM_CONFIG_PATH: /stage/metricConfigs 15 | volumes: 16 | - ./serverSrc:/stage/serverSrc 17 | - ./clientSrc:/stage/clientSrc 18 | - ./config/metricConfigs:/stage/metricConfigs 19 | 20 | # prod-server: 21 | # build: 22 | # context: . 23 | # dockerfile: Dockerfile 24 | # ports: 25 | # - 3000:3000 26 | # # Note: in production you should not expose port 9102. It is exposed here just to make it easier to manually verify GET :9102/metrics 27 | # - 9102:9102 28 | # environment: 29 | # PUM_CONFIG_PATH: /stage/metricConfigs 30 | # volumes: 31 | # - ./config/metricConfigs:/stage/metricConfigs 32 | 33 | demo-prom: 34 | image: prom/prometheus 35 | command: 36 | - -config.file=/prometheusConfig/prometheus.yml 37 | ports: 38 | - 9090:9090 39 | volumes: 40 | - ./demo/prometheusConfig:/prometheusConfig 41 | links: 42 | - dev-server:metrics-aggregator-dev-server 43 | 44 | demo-grafana: 45 | image: grafana/grafana 46 | ports: 47 | - 3001:3000 48 | volumes: 49 | - ./demo/grafanaConfig:/grafana-data 50 | links: 51 | - demo-prom 52 | environment: 53 | GF_AUTH_BASIC_ENABLED: "false" 54 | GF_AUTH_ANONYMOUS_ENABLED: "true" 55 | GF_AUTH_ANONYMOUS_ORG_ROLE: Admin 56 | GF_PATHS_DATA: /grafana-data 57 | 58 | # This server actually serves the demo code 59 | sample-web-server: 60 | image: nginx 61 | ports: 62 | - 8080:80 63 | volumes: 64 | - ./demo/sampleApp:/usr/share/nginx/html:ro -------------------------------------------------------------------------------- /navigationtiming.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peardeck/prometheus-user-metrics/3fda55db01d9f297d1a9995ce6ab3535d450b35e/navigationtiming.png -------------------------------------------------------------------------------- /runDevServer.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | babel clientSrc/aggregatorClient.js --watch --out-file static/aggregatorClient.js & 4 | babel-watch serverSrc/server.js -------------------------------------------------------------------------------- /serverPackage.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "metrics-aggregator", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "author": "", 10 | "license": "ISC", 11 | "dependencies": { 12 | "body-parser": "^1.17.0", 13 | "express": "^4.15.0" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /serverSrc/.flowconfig: -------------------------------------------------------------------------------- 1 | [ignore] 2 | 3 | [include] 4 | 5 | [libs] 6 | 7 | [options] 8 | -------------------------------------------------------------------------------- /serverSrc/__tests__/reportingTests.js: -------------------------------------------------------------------------------- 1 | import { makeAggregator } from '../makeMetricsAggregator'; 2 | 3 | const exampleConfig = [ 4 | { 5 | "name": "usage_total", 6 | "help": "counts of usage, like times a feature has been used, etc", 7 | "type": "counter", 8 | "labels": [ 9 | { 10 | "name": "browser", 11 | "allowedValues": [ 12 | "chrome", 13 | "firefox", 14 | "safari", 15 | "edge" 16 | ] 17 | }, 18 | { 19 | "name": "feature", 20 | "allowedValues": [ 21 | "quickQuestion", 22 | "selfPacedMode", 23 | "blockStudent", 24 | "showContent" 25 | ] 26 | } 27 | ] 28 | }, 29 | { 30 | "name": "firebase_response_time", 31 | "help": "measures firebase response times in seconds", 32 | "type": "histogram", 33 | "labels": [ 34 | { 35 | "name": "firebaseHost", 36 | "allowedValues": [ 37 | "pd-dev-1.firebaseio.com", 38 | "pd-dev-2.firebaseio.com" 39 | ] 40 | } 41 | ], 42 | "buckets": [ 43 | 0.05, 44 | 0.1, 45 | 0.2, 46 | 0.5, 47 | 1, 48 | 2, 49 | 5, 50 | 10, 51 | 20, 52 | 50, 53 | 100 54 | ] 55 | } 56 | ]; 57 | 58 | function outputWithUsageTotal(usageTotal) { 59 | return `# HELP usage_total counts of usage, like times a feature has been used, etc 60 | # TYPE usage_total counter 61 | usage_total{browser="chrome",feature="quickQuestion"} ${usageTotal} 62 | usage_total{browser="chrome",feature="selfPacedMode"} 0 63 | usage_total{browser="chrome",feature="blockStudent"} 0 64 | usage_total{browser="chrome",feature="showContent"} 0 65 | usage_total{browser="firefox",feature="quickQuestion"} 0 66 | usage_total{browser="firefox",feature="selfPacedMode"} 0 67 | usage_total{browser="firefox",feature="blockStudent"} 0 68 | usage_total{browser="firefox",feature="showContent"} 0 69 | usage_total{browser="safari",feature="quickQuestion"} 0 70 | usage_total{browser="safari",feature="selfPacedMode"} 0 71 | usage_total{browser="safari",feature="blockStudent"} 0 72 | usage_total{browser="safari",feature="showContent"} 0 73 | usage_total{browser="edge",feature="quickQuestion"} 0 74 | usage_total{browser="edge",feature="selfPacedMode"} 0 75 | usage_total{browser="edge",feature="blockStudent"} 0 76 | usage_total{browser="edge",feature="showContent"} 0 77 | # HELP firebase_response_time measures firebase response times in seconds 78 | # TYPE firebase_response_time histogram 79 | firebase_response_time_bucket{firebaseHost="pd-dev-1.firebaseio.com",le="0.05"} 0 80 | firebase_response_time_bucket{firebaseHost="pd-dev-1.firebaseio.com",le="0.1"} 0 81 | firebase_response_time_bucket{firebaseHost="pd-dev-1.firebaseio.com",le="0.2"} 0 82 | firebase_response_time_bucket{firebaseHost="pd-dev-1.firebaseio.com",le="0.5"} 0 83 | firebase_response_time_bucket{firebaseHost="pd-dev-1.firebaseio.com",le="1"} 0 84 | firebase_response_time_bucket{firebaseHost="pd-dev-1.firebaseio.com",le="2"} 0 85 | firebase_response_time_bucket{firebaseHost="pd-dev-1.firebaseio.com",le="5"} 0 86 | firebase_response_time_bucket{firebaseHost="pd-dev-1.firebaseio.com",le="10"} 0 87 | firebase_response_time_bucket{firebaseHost="pd-dev-1.firebaseio.com",le="20"} 0 88 | firebase_response_time_bucket{firebaseHost="pd-dev-1.firebaseio.com",le="50"} 0 89 | firebase_response_time_bucket{firebaseHost="pd-dev-1.firebaseio.com",le="100"} 0 90 | firebase_response_time_bucket{firebaseHost="pd-dev-1.firebaseio.com",le="+Inf"} 0 91 | firebase_response_time_sum{firebaseHost="pd-dev-1.firebaseio.com"} 0 92 | firebase_response_time_count{firebaseHost="pd-dev-1.firebaseio.com"} 0 93 | firebase_response_time_bucket{firebaseHost="pd-dev-2.firebaseio.com",le="0.05"} 0 94 | firebase_response_time_bucket{firebaseHost="pd-dev-2.firebaseio.com",le="0.1"} 0 95 | firebase_response_time_bucket{firebaseHost="pd-dev-2.firebaseio.com",le="0.2"} 0 96 | firebase_response_time_bucket{firebaseHost="pd-dev-2.firebaseio.com",le="0.5"} 0 97 | firebase_response_time_bucket{firebaseHost="pd-dev-2.firebaseio.com",le="1"} 0 98 | firebase_response_time_bucket{firebaseHost="pd-dev-2.firebaseio.com",le="2"} 0 99 | firebase_response_time_bucket{firebaseHost="pd-dev-2.firebaseio.com",le="5"} 0 100 | firebase_response_time_bucket{firebaseHost="pd-dev-2.firebaseio.com",le="10"} 0 101 | firebase_response_time_bucket{firebaseHost="pd-dev-2.firebaseio.com",le="20"} 0 102 | firebase_response_time_bucket{firebaseHost="pd-dev-2.firebaseio.com",le="50"} 0 103 | firebase_response_time_bucket{firebaseHost="pd-dev-2.firebaseio.com",le="100"} 0 104 | firebase_response_time_bucket{firebaseHost="pd-dev-2.firebaseio.com",le="+Inf"} 0 105 | firebase_response_time_sum{firebaseHost="pd-dev-2.firebaseio.com"} 0 106 | firebase_response_time_count{firebaseHost="pd-dev-2.firebaseio.com"} 0 107 | `; 108 | } 109 | 110 | const usageTotalKey = 'usage_total{browser="chrome",feature="quickQuestion"}'; 111 | 112 | describe('Aggregator reporting', () => { 113 | it('prints a correct default', () => { 114 | const aggregator = makeAggregator(exampleConfig); 115 | expect(aggregator.reportMetrics()).toBe(outputWithUsageTotal(0)); 116 | }); 117 | 118 | it('correctly increments uninitialized counters', () => { 119 | const aggregator = makeAggregator(exampleConfig); 120 | aggregator.consume({ 121 | metricName: 'usage_total', 122 | metricType: 'counter', 123 | labels: { 124 | browser: 'chrome', 125 | feature: 'quickQuestion', 126 | }, 127 | inc: 3.5 128 | }); 129 | 130 | expect(aggregator.reportMetrics()).toBe(outputWithUsageTotal(3.5)); 131 | }); 132 | 133 | it('correctly increments initialized counters', () => { 134 | const aggregator = makeAggregator(exampleConfig); 135 | aggregator.consume({ 136 | metricName: 'usage_total', 137 | metricType: 'counter', 138 | labels: { 139 | browser: 'chrome', 140 | feature: 'quickQuestion', 141 | }, 142 | inc: 3.5 143 | }); 144 | aggregator.consume({ 145 | metricName: 'usage_total', 146 | metricType: 'counter', 147 | labels: { 148 | browser: 'chrome', 149 | feature: 'quickQuestion', 150 | }, 151 | inc: 3.5 152 | }); 153 | expect(aggregator.reportMetrics()).toBe(outputWithUsageTotal(7)); 154 | }); 155 | 156 | it('correctly records observations of histograms', () => { 157 | const aggregator = makeAggregator(exampleConfig); 158 | 159 | const expected = `# HELP usage_total counts of usage, like times a feature has been used, etc 160 | # TYPE usage_total counter 161 | usage_total{browser="chrome",feature="quickQuestion"} 0 162 | usage_total{browser="chrome",feature="selfPacedMode"} 0 163 | usage_total{browser="chrome",feature="blockStudent"} 0 164 | usage_total{browser="chrome",feature="showContent"} 0 165 | usage_total{browser="firefox",feature="quickQuestion"} 0 166 | usage_total{browser="firefox",feature="selfPacedMode"} 0 167 | usage_total{browser="firefox",feature="blockStudent"} 0 168 | usage_total{browser="firefox",feature="showContent"} 0 169 | usage_total{browser="safari",feature="quickQuestion"} 0 170 | usage_total{browser="safari",feature="selfPacedMode"} 0 171 | usage_total{browser="safari",feature="blockStudent"} 0 172 | usage_total{browser="safari",feature="showContent"} 0 173 | usage_total{browser="edge",feature="quickQuestion"} 0 174 | usage_total{browser="edge",feature="selfPacedMode"} 0 175 | usage_total{browser="edge",feature="blockStudent"} 0 176 | usage_total{browser="edge",feature="showContent"} 0 177 | # HELP firebase_response_time measures firebase response times in seconds 178 | # TYPE firebase_response_time histogram 179 | firebase_response_time_bucket{firebaseHost="pd-dev-1.firebaseio.com",le="0.05"} 1 180 | firebase_response_time_bucket{firebaseHost="pd-dev-1.firebaseio.com",le="0.1"} 2 181 | firebase_response_time_bucket{firebaseHost="pd-dev-1.firebaseio.com",le="0.2"} 2 182 | firebase_response_time_bucket{firebaseHost="pd-dev-1.firebaseio.com",le="0.5"} 3 183 | firebase_response_time_bucket{firebaseHost="pd-dev-1.firebaseio.com",le="1"} 3 184 | firebase_response_time_bucket{firebaseHost="pd-dev-1.firebaseio.com",le="2"} 3 185 | firebase_response_time_bucket{firebaseHost="pd-dev-1.firebaseio.com",le="5"} 3 186 | firebase_response_time_bucket{firebaseHost="pd-dev-1.firebaseio.com",le="10"} 3 187 | firebase_response_time_bucket{firebaseHost="pd-dev-1.firebaseio.com",le="20"} 3 188 | firebase_response_time_bucket{firebaseHost="pd-dev-1.firebaseio.com",le="50"} 3 189 | firebase_response_time_bucket{firebaseHost="pd-dev-1.firebaseio.com",le="100"} 3 190 | firebase_response_time_bucket{firebaseHost="pd-dev-1.firebaseio.com",le="+Inf"} 3 191 | firebase_response_time_sum{firebaseHost="pd-dev-1.firebaseio.com"} 0.45 192 | firebase_response_time_count{firebaseHost="pd-dev-1.firebaseio.com"} 3 193 | firebase_response_time_bucket{firebaseHost="pd-dev-2.firebaseio.com",le="0.05"} 0 194 | firebase_response_time_bucket{firebaseHost="pd-dev-2.firebaseio.com",le="0.1"} 0 195 | firebase_response_time_bucket{firebaseHost="pd-dev-2.firebaseio.com",le="0.2"} 0 196 | firebase_response_time_bucket{firebaseHost="pd-dev-2.firebaseio.com",le="0.5"} 0 197 | firebase_response_time_bucket{firebaseHost="pd-dev-2.firebaseio.com",le="1"} 0 198 | firebase_response_time_bucket{firebaseHost="pd-dev-2.firebaseio.com",le="2"} 0 199 | firebase_response_time_bucket{firebaseHost="pd-dev-2.firebaseio.com",le="5"} 0 200 | firebase_response_time_bucket{firebaseHost="pd-dev-2.firebaseio.com",le="10"} 0 201 | firebase_response_time_bucket{firebaseHost="pd-dev-2.firebaseio.com",le="20"} 0 202 | firebase_response_time_bucket{firebaseHost="pd-dev-2.firebaseio.com",le="50"} 0 203 | firebase_response_time_bucket{firebaseHost="pd-dev-2.firebaseio.com",le="100"} 0 204 | firebase_response_time_bucket{firebaseHost="pd-dev-2.firebaseio.com",le="+Inf"} 0 205 | firebase_response_time_sum{firebaseHost="pd-dev-2.firebaseio.com"} 0 206 | firebase_response_time_count{firebaseHost="pd-dev-2.firebaseio.com"} 0 207 | `; 208 | 209 | aggregator.consume({ 210 | metricName: 'firebase_response_time', 211 | metricType: 'histogram', 212 | labels: { 213 | firebaseHost: 'pd-dev-1.firebaseio.com', 214 | }, 215 | observations: [0.1, 0.3, 0.05] 216 | }); 217 | 218 | expect(aggregator.reportMetrics()).toBe(expected); 219 | }) 220 | }); -------------------------------------------------------------------------------- /serverSrc/aggregators/__tests__/counterTest.js: -------------------------------------------------------------------------------- 1 | /* @flow */ 2 | import { makeCounter } from '../counter'; 3 | 4 | 5 | declare type Expectable = { 6 | toBe: (t: T) => void; 7 | toBeNull: () => void; 8 | toBeTruthy: () => void; 9 | toBeFalsy: () => void; 10 | toContain: (t: any) => void; 11 | toEqual: (t: T) => void; 12 | not: Expectable; 13 | } 14 | 15 | declare type DoneCb = () => void; 16 | 17 | declare function beforeAll(prepare: ((done: DoneCb) => void)): void; 18 | declare function describe(description: string, tests: (() => void)): void; 19 | declare function fdescribe(description: string, tests: (() => void)): void; 20 | declare function xdescribe(description: string, tests: (() => void)): void; 21 | declare function it(description: string, test: ((done: DoneCb) => void)): void; 22 | declare function xit(description: string, test: ((done: DoneCb) => void)): void; 23 | declare function fit(description: string, test: ((done: DoneCb) => void)): void; 24 | declare function expect(x: T): Expectable; 25 | declare function fail(description: string): void; 26 | 27 | 28 | describe('Counters', () => { 29 | const counterConfig = { 30 | "name": "usage_total", 31 | "help": "counts of usage, like times a feature has been used, etc", 32 | "type": "counter", 33 | "labels": [ 34 | { 35 | "name": "browser", 36 | "allowedValues": [ 37 | "chrome", 38 | "firefox", 39 | "safari", 40 | "edge" 41 | ] 42 | }, 43 | { 44 | "name": "feature", 45 | "allowedValues": [ 46 | "quickQuestion", 47 | "selfPacedMode", 48 | "blockStudent", 49 | "showContent" 50 | ] 51 | } 52 | ] 53 | }; 54 | 55 | it ('has this test', () => { 56 | const counter = makeCounter(counterConfig); 57 | counter.record({ 58 | metricType: 'counter', 59 | metricName: 'usage_total', 60 | labels: { browser: 'chrome', feature: 'selfPacedMode' }, 61 | inc: 5 62 | }); 63 | 64 | counter.record({ 65 | metricType: 'counter', 66 | metricName: 'usage_total', 67 | labels: { browser: 'firefox', feature: 'selfPacedMode' }, 68 | inc: 3 69 | }); 70 | 71 | counter.record({ 72 | metricType: 'counter', 73 | metricName: 'usage_total', 74 | labels: { browser: 'chrome', feature: 'selfPacedMode' }, 75 | inc: 1 76 | }); 77 | 78 | const expected = `# HELP usage_total counts of usage, like times a feature has been used, etc 79 | # TYPE usage_total counter 80 | usage_total{browser="chrome",feature="quickQuestion"} 0 81 | usage_total{browser="chrome",feature="selfPacedMode"} 6 82 | usage_total{browser="chrome",feature="blockStudent"} 0 83 | usage_total{browser="chrome",feature="showContent"} 0 84 | usage_total{browser="firefox",feature="quickQuestion"} 0 85 | usage_total{browser="firefox",feature="selfPacedMode"} 3 86 | usage_total{browser="firefox",feature="blockStudent"} 0 87 | usage_total{browser="firefox",feature="showContent"} 0 88 | usage_total{browser="safari",feature="quickQuestion"} 0 89 | usage_total{browser="safari",feature="selfPacedMode"} 0 90 | usage_total{browser="safari",feature="blockStudent"} 0 91 | usage_total{browser="safari",feature="showContent"} 0 92 | usage_total{browser="edge",feature="quickQuestion"} 0 93 | usage_total{browser="edge",feature="selfPacedMode"} 0 94 | usage_total{browser="edge",feature="blockStudent"} 0 95 | usage_total{browser="edge",feature="showContent"} 0` 96 | expect(counter.report()).toBe(expected); 97 | }) 98 | }) -------------------------------------------------------------------------------- /serverSrc/aggregators/__tests__/histogramTest.js: -------------------------------------------------------------------------------- 1 | /* @flow */ 2 | import { makeHistogram } from '../histogram'; 3 | 4 | 5 | declare type Expectable = { 6 | toBe: (t: T) => void; 7 | toBeNull: () => void; 8 | toBeTruthy: () => void; 9 | toBeFalsy: () => void; 10 | toContain: (t: any) => void; 11 | toEqual: (t: T) => void; 12 | not: Expectable; 13 | } 14 | 15 | declare type DoneCb = () => void; 16 | 17 | declare function beforeAll(prepare: ((done: DoneCb) => void)): void; 18 | declare function describe(description: string, tests: (() => void)): void; 19 | declare function fdescribe(description: string, tests: (() => void)): void; 20 | declare function xdescribe(description: string, tests: (() => void)): void; 21 | declare function it(description: string, test: ((done: DoneCb) => void)): void; 22 | declare function xit(description: string, test: ((done: DoneCb) => void)): void; 23 | declare function fit(description: string, test: ((done: DoneCb) => void)): void; 24 | declare function expect(x: T): Expectable; 25 | declare function fail(description: string): void; 26 | 27 | 28 | describe('Histograms', () => { 29 | const histogramConfig = { 30 | "name": "firebase_response_time", 31 | "help": "measures firebase response times in seconds", 32 | "type": "histogram", 33 | "labels": [ 34 | { 35 | "name": "firebaseHost", 36 | "allowedValues": [ 37 | "pd-dev-1.firebaseio.com", 38 | "pd-dev-2.firebaseio.com" 39 | ] 40 | } 41 | ], 42 | "buckets": [ 43 | 0.05, 44 | 0.1, 45 | 0.2, 46 | 0.5, 47 | 1, 48 | 2, 49 | 5, 50 | 10, 51 | 20, 52 | 50, 53 | 100 54 | ] 55 | }; 56 | 57 | it('has this test', () => { 58 | const histogram = makeHistogram(histogramConfig); 59 | 60 | histogram.record({ 61 | metricType: 'histogram', 62 | metricName: 'firebase_response_time', 63 | labels: { firebaseHost: 'pd-dev-1.firebaseio.com' }, 64 | observations: [0.1, 1, 3] 65 | }); 66 | 67 | histogram.record({ 68 | metricType: 'histogram', 69 | metricName: 'firebase_response_time', 70 | labels: { firebaseHost: 'pd-dev-1.firebaseio.com' }, 71 | observations: [5, 9, 2] 72 | }); 73 | 74 | histogram.record({ 75 | metricType: 'histogram', 76 | metricName: 'firebase_response_time', 77 | labels: { firebaseHost: 'pd-dev-2.firebaseio.com' }, 78 | observations: [15, 19, 12] 79 | }); 80 | 81 | const expected = `# HELP firebase_response_time measures firebase response times in seconds 82 | # TYPE firebase_response_time histogram 83 | firebase_response_time_bucket{firebaseHost="pd-dev-1.firebaseio.com",le="0.05"} 0 84 | firebase_response_time_bucket{firebaseHost="pd-dev-1.firebaseio.com",le="0.1"} 1 85 | firebase_response_time_bucket{firebaseHost="pd-dev-1.firebaseio.com",le="0.2"} 1 86 | firebase_response_time_bucket{firebaseHost="pd-dev-1.firebaseio.com",le="0.5"} 1 87 | firebase_response_time_bucket{firebaseHost="pd-dev-1.firebaseio.com",le="1"} 2 88 | firebase_response_time_bucket{firebaseHost="pd-dev-1.firebaseio.com",le="2"} 3 89 | firebase_response_time_bucket{firebaseHost="pd-dev-1.firebaseio.com",le="5"} 5 90 | firebase_response_time_bucket{firebaseHost="pd-dev-1.firebaseio.com",le="10"} 6 91 | firebase_response_time_bucket{firebaseHost="pd-dev-1.firebaseio.com",le="20"} 6 92 | firebase_response_time_bucket{firebaseHost="pd-dev-1.firebaseio.com",le="50"} 6 93 | firebase_response_time_bucket{firebaseHost="pd-dev-1.firebaseio.com",le="100"} 6 94 | firebase_response_time_bucket{firebaseHost="pd-dev-1.firebaseio.com",le="+Inf"} 6 95 | firebase_response_time_sum{firebaseHost="pd-dev-1.firebaseio.com"} 20.1 96 | firebase_response_time_count{firebaseHost="pd-dev-1.firebaseio.com"} 6 97 | firebase_response_time_bucket{firebaseHost="pd-dev-2.firebaseio.com",le="0.05"} 0 98 | firebase_response_time_bucket{firebaseHost="pd-dev-2.firebaseio.com",le="0.1"} 0 99 | firebase_response_time_bucket{firebaseHost="pd-dev-2.firebaseio.com",le="0.2"} 0 100 | firebase_response_time_bucket{firebaseHost="pd-dev-2.firebaseio.com",le="0.5"} 0 101 | firebase_response_time_bucket{firebaseHost="pd-dev-2.firebaseio.com",le="1"} 0 102 | firebase_response_time_bucket{firebaseHost="pd-dev-2.firebaseio.com",le="2"} 0 103 | firebase_response_time_bucket{firebaseHost="pd-dev-2.firebaseio.com",le="5"} 0 104 | firebase_response_time_bucket{firebaseHost="pd-dev-2.firebaseio.com",le="10"} 0 105 | firebase_response_time_bucket{firebaseHost="pd-dev-2.firebaseio.com",le="20"} 3 106 | firebase_response_time_bucket{firebaseHost="pd-dev-2.firebaseio.com",le="50"} 3 107 | firebase_response_time_bucket{firebaseHost="pd-dev-2.firebaseio.com",le="100"} 3 108 | firebase_response_time_bucket{firebaseHost="pd-dev-2.firebaseio.com",le="+Inf"} 3 109 | firebase_response_time_sum{firebaseHost="pd-dev-2.firebaseio.com"} 46 110 | firebase_response_time_count{firebaseHost="pd-dev-2.firebaseio.com"} 3`; 111 | 112 | expect(histogram.report()).toBe(expected); 113 | }) 114 | }) -------------------------------------------------------------------------------- /serverSrc/aggregators/counter.js: -------------------------------------------------------------------------------- 1 | /* @flow */ 2 | 3 | import { getLabelPermutations, flattenLabels } from './util'; 4 | import type { CounterMetric, CounterEvent } from './util'; 5 | 6 | export type Counter = { 7 | record: (event: CounterEvent) => void, 8 | report: () => string, 9 | }; 10 | 11 | export function makeCounter(config: CounterMetric) : Counter { 12 | const { name, help, type } = config; 13 | 14 | const allowedLabelPermutations = getLabelPermutations(config.labels); 15 | const counterValues = {}; 16 | allowedLabelPermutations.forEach((permutation) => { 17 | // initialize all allowed permutations to zero. 18 | counterValues[permutation] = 0; 19 | 20 | // later, all other permutations will be rejected, so this 21 | // secures the counters against misbehaving clients who would 22 | // send unknown labels or values and crash poor prometheus. 23 | }); 24 | 25 | return { 26 | record(event: CounterEvent) { 27 | const labelPermutationKey = flattenLabels(event.labels); 28 | if (typeof counterValues[labelPermutationKey] === 'number') { 29 | counterValues[labelPermutationKey] += event.inc; 30 | } else { 31 | console.log(`Disallowed label permutation ${labelPermutationKey}`); 32 | } 33 | }, 34 | 35 | report() { 36 | let headerLines = [ 37 | `# HELP ${name} ${help}`, 38 | `# TYPE ${name} ${type}` 39 | ]; 40 | 41 | let bodyLines = Object.keys(counterValues).map((labelPermutationKey) => { 42 | const value = counterValues[labelPermutationKey]; 43 | return `${name}{${labelPermutationKey}} ${value}`; 44 | }); 45 | 46 | return headerLines.join('\n') + '\n' + bodyLines.join('\n'); 47 | } 48 | } 49 | } -------------------------------------------------------------------------------- /serverSrc/aggregators/histogram.js: -------------------------------------------------------------------------------- 1 | /* @flow */ 2 | 3 | import { getLabelPermutations, flattenLabels } from './util'; 4 | import type { HistogramMetric, HistogramEvent, Label } from './util'; 5 | 6 | 7 | type HistogramObservationAggregate = { 8 | buckets: {[bucketLimit: string]: number}, // Note, "+Inf" won't be kept in here. We'll just report `sum` as +Inf synthetically when printing this aggregate. 9 | sum: number, 10 | count: number 11 | }; 12 | 13 | function addObservation(aggregate: HistogramObservationAggregate, newObservation: number) { 14 | Object.keys(aggregate.buckets).forEach((bucketLimit) => { 15 | if (newObservation <= Number(bucketLimit)) { 16 | aggregate.buckets[bucketLimit]++; 17 | } 18 | }); 19 | 20 | aggregate.count++; 21 | aggregate.sum += newObservation; 22 | } 23 | 24 | function printObservationAggregate(metricName: string, labelPermutationKey: string, aggregate: HistogramObservationAggregate) { 25 | const leKeys = Object.keys(aggregate.buckets).sort((a, b) => Number(a) < Number(b) ? -1 : 1); 26 | const labelStringPrefix = labelPermutationKey.length > 0 27 | ? `${labelPermutationKey},` // stick labels in front of new `le` label with a comma 28 | : ''; // no labels, no comma. 29 | 30 | const bucketLines = leKeys.map((bucketLimit) => { 31 | return `${metricName}_bucket{${labelStringPrefix}le="${bucketLimit}"} ${aggregate.buckets[bucketLimit]}`; 32 | }); 33 | 34 | return bucketLines.join('\n') + '\n' + 35 | `${metricName}_bucket{${labelStringPrefix}le="+Inf"} ${aggregate.count}` + '\n' + 36 | `${metricName}_sum{${labelPermutationKey}} ${aggregate.sum}` + '\n' + 37 | `${metricName}_count{${labelPermutationKey}} ${aggregate.count}`; 38 | } 39 | 40 | export type Histogram = { 41 | record: (event: HistogramEvent) => void, 42 | report: () => string 43 | }; 44 | 45 | export function makeHistogram(config: HistogramMetric): Histogram { 46 | const { name, help, type } = config; 47 | 48 | const allowedLabelPermutations = getLabelPermutations(config.labels); 49 | 50 | const mapOfAggregates: {[key: string]: HistogramObservationAggregate} = {}; 51 | 52 | allowedLabelPermutations.forEach((permutation) => { 53 | // initialize all allowed permutations to a bunch of empty buckets. 54 | const initializedAggregate:HistogramObservationAggregate = { 55 | buckets: {}, 56 | sum: 0, 57 | count: 0, 58 | } 59 | 60 | config.buckets.forEach((bucketLimit) => { 61 | initializedAggregate.buckets[bucketLimit.toString()] = 0; 62 | }); 63 | 64 | mapOfAggregates[permutation] = initializedAggregate; 65 | 66 | // later, all other permutations will be rejected, so this 67 | // secures the counters against misbehaving clients who would 68 | // send unknown labels or values and crash poor prometheus. 69 | }); 70 | 71 | return { 72 | record(event: HistogramEvent) { 73 | const labelPermutationKey = flattenLabels(event.labels); 74 | if (mapOfAggregates[labelPermutationKey]) { 75 | event.observations.forEach((observation) => { 76 | addObservation(mapOfAggregates[labelPermutationKey], observation); 77 | }); 78 | 79 | } else { 80 | console.log(`Disallowed label permutation ${labelPermutationKey}`); 81 | } 82 | }, 83 | 84 | report() { 85 | let headerLines = [ 86 | `# HELP ${name} ${help}`, 87 | `# TYPE ${name} ${type}` 88 | ]; 89 | 90 | let bodyLines = Object.keys(mapOfAggregates).map((labelPermutationKey) => { 91 | const aggregate = mapOfAggregates[labelPermutationKey]; 92 | return printObservationAggregate(name, labelPermutationKey, aggregate); 93 | }); 94 | 95 | return headerLines.join('\n') + '\n' + bodyLines.join('\n'); 96 | } 97 | } 98 | } -------------------------------------------------------------------------------- /serverSrc/aggregators/util.js: -------------------------------------------------------------------------------- 1 | /* @flow */ 2 | 3 | export type Label = { 4 | name: string, 5 | allowedValues: Array 6 | }; 7 | 8 | export type Metric = { 9 | name: string, 10 | help: string, 11 | labels: Array