├── .gitignore ├── .gitmodules ├── LICENSE ├── README.md ├── porkchop ├── __init__.py ├── backend.py ├── commandline.py ├── plugin.py ├── server.py └── util.py └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | dist 2 | *.egg-info 3 | *.pyc 4 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "porkchop/plugins"] 2 | path = porkchop/plugins 3 | url = git@github.com:disqus/porkchop-plugins.git 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2011 DISQUS 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Porkchop 2 | 3 | Porkchop is a simple HTTP-based system information server. You write plugins 4 | for it and it responds with the data based on your request. 5 | 6 | Here is an example: 7 | 8 | scott@beatbox:~% curl http://localhost:5000/cpuinfo 9 | /cpuinfo/processor2/fpu yes 10 | /cpuinfo/processor2/f00f_bug no 11 | /cpuinfo/processor2/cache_alignment 64 12 | /cpuinfo/processor2/vendor_id AuthenticAMD 13 | /cpuinfo/processor2/flags fpu 14 | /cpuinfo/processor2/bogomips 6384 15 | /cpuinfo/processor2/hlt_bug no 16 | /cpuinfo/processor2/apicid 2 17 | /cpuinfo/processor2/fpu_exception yes 18 | /cpuinfo/processor2/stepping 3 19 | /cpuinfo/processor2/wp yes 20 | /cpuinfo/processor2/siblings 4 21 | /cpuinfo/processor2/model 4 22 | /cpuinfo/processor2/coma_bug no 23 | /cpuinfo/processor2/fdiv_bug no 24 | /cpuinfo/processor3/fpu yes 25 | /cpuinfo/processor3/f00f_bug no 26 | /cpuinfo/processor3/cache_alignment 64 27 | /cpuinfo/processor3/vendor_id AuthenticAMD 28 | /cpuinfo/processor3/flags fpu 29 | /cpuinfo/processor3/bogomips 6384 30 | /cpuinfo/processor3/hlt_bug no 31 | /cpuinfo/processor3/apicid 3 32 | /cpuinfo/processor3/fpu_exception yes 33 | /cpuinfo/processor3/stepping 3 34 | /cpuinfo/processor3/wp yes 35 | /cpuinfo/processor3/siblings 4 36 | /cpuinfo/processor3/model 4 37 | /cpuinfo/processor3/coma_bug no 38 | /cpuinfo/processor3/fdiv_bug no 39 | [snip] 40 | /time 1311387215 41 | scott@beatbox:~% 42 | 43 | It can also respond with JSON via .json file extension or setting the ```Accept: application/json``` header. 44 | 45 | scott@beatbox:~% curl http://localhost:5000/cpuinfo.json 46 | {"cpuinfo": {"processor2": {"fpu": "yes", "f00f_bug": "no", "cache_alignment": "64", "vendor_id": "AuthenticAMD", "flags": "fpu", "bogomips": "6384", "hlt_bug": "no", "apicid": "2", "fpu_exception": "yes", "stepping": "3", "wp": "yes", "siblings": "4", "model": "4", "coma_bug": "no", "fdiv_bug": "no"}, "processor3": {"fpu": "yes", "f00f_bug": "no", "cache_alignment": "64", "vendor_id": "AuthenticAMD", "flags": "fpu", "bogomips": "6384", "hlt_bug": "no", "apicid": "3", "fpu_exception": "yes", "stepping": "3", "wp": "yes", "siblings": "4", "model": "4", "coma_bug": "no", "fdiv_bug": "no"}, "processor0": {"fpu": "yes", "f00f_bug": "no", "cache_alignment": "64", "vendor_id": "AuthenticAMD", "flags": "fpu", "bogomips": "6382", "hlt_bug": "no", "apicid": "0", "fpu_exception": "yes", "stepping": "3", "wp": "yes", "siblings": "4", "model": "4", "coma_bug": "no", "fdiv_bug": "no"}, "processor1": {"fpu": "yes", "f00f_bug": "no", "cache_alignment": "64", "vendor_id": "AuthenticAMD", "flags": "fpu", "bogomips": "6384", "hlt_bug": "no", "apicid": "1", "fpu_exception": "yes", "stepping": "3", "wp": "yes", "siblings": "4", "model": "4", "coma_bug": "no", "fdiv_bug": "no"}}, "time": "1311389934"} 47 | scott@beatbox:~% 48 | 49 | ## Installation 50 | 51 | pip install porkchop 52 | 53 | or 54 | 55 | git clone git://github.com/disqus/porkchop.git 56 | cd porkchop 57 | git submodule init && git submodule update 58 | python setup.py install 59 | 60 | 61 | ### Extra Packages 62 | 63 | to use the redis or thoonk plugins, you must have redis>=2.4.10 installed. 64 | 65 | 66 | ## Running Porkchop 67 | 68 | porkchop 69 | 70 | ## Writing Plugins 71 | 72 | It's pretty easy to write a new plugin. They're just Python modules with some common attributes: 73 | 74 | * A plugin must subclass ```porkchop.plugin.PorkchopPlugin```. 75 | * The plugin's class must contain a method called ```get_data``` that returns a dictionary of the information to be displayed. 76 | * The plugin's metric name will be derived from the module name (N.B. this means you'll only be able to define one plugin per module). To override the metric name, you may set the magic ```__metric_name__``` property on the plugin. 77 | 78 | By default, a plugin's ```get_data``` method will only be called if the data is more then 60 seconds old. This can be changed on a per-plugin basis by setting ```self.refresh``` in the class's ```___init___``` method. 79 | 80 | These plugins can be placed in any directory you choose, and loaded by passing the ```-d [dir]``` option to porkchop. 81 | -------------------------------------------------------------------------------- /porkchop/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/disqus/porkchop/32458d0a2c1557f765c4c9734feb931546c1e3ef/porkchop/__init__.py -------------------------------------------------------------------------------- /porkchop/backend.py: -------------------------------------------------------------------------------- 1 | """ 2 | porkchop.backend 3 | ~~~~~~~~~~~~~~~~ 4 | 5 | :copyright: (c) 2011-2012 DISQUS. 6 | :license: Apache License 2.0, see LICENSE for more details. 7 | """ 8 | import socket 9 | import struct 10 | import time 11 | import cPickle 12 | 13 | 14 | class Carbon(object): 15 | def __init__(self, host, port, logger): 16 | self.data = {} 17 | self.host = host 18 | self.port = port 19 | self.logger = logger 20 | try: 21 | self.sock = self._connect() 22 | except socket.error: 23 | self.logger.fatal('Unable to connect to carbon.') 24 | 25 | def _connect(self, waittime=5): 26 | self.logger.info('Connecting to carbon on %s:%d', self.host, self.port) 27 | try: 28 | sock = socket.socket() 29 | sock.connect((self.host, self.port)) 30 | except socket.error: 31 | self.logger.info('Unable to connect to carbon, retrying in %d seconds', waittime) 32 | time.sleep(waittime) 33 | self._connect(waittime + 5) 34 | 35 | return sock 36 | 37 | def _send(self, data): 38 | try: 39 | self.sock.sendall(self._serialize(data.items())) 40 | except socket.error: 41 | raise 42 | 43 | def _serialize(self, data): 44 | serialized = cPickle.dumps(data, protocol=-1) 45 | prefix = struct.pack('!L', len(serialized)) 46 | return prefix + serialized 47 | 48 | def send(self): 49 | """ self.data format: {metric_name: [(t1, val1), (t2, val2)]} """ 50 | buf_sz = 500 51 | to_send = {} 52 | 53 | for mn in self.data.iterkeys(): 54 | while len(self.data[mn]) > 0: 55 | l = len(to_send) 56 | if l < buf_sz: 57 | to_send.setdefault(mn, []) 58 | to_send[mn].append(self.data[mn].pop()) 59 | else: 60 | try: 61 | self._send(to_send) 62 | to_send = {} 63 | to_send.setdefault(mn, []) 64 | to_send[mn].append(self.data[mn].pop()) 65 | except socket.error: 66 | self.logger.error('Error sending to carbon, trying to reconnect.') 67 | self.sock = self._connect() 68 | 69 | # we failed to send, so put it back in the stack and try later 70 | for ent in to_send: 71 | self.data[ent[0]].append(ent[1]) 72 | 73 | try: 74 | self._send(to_send) 75 | except socket.error: 76 | self.logger.error('Error sending to carbon, trying to reconnect.') 77 | self.sock = self._connect() 78 | 79 | # we failed to send, so put it back in the stack and try later 80 | for ent in to_send: 81 | self.data[ent[0]].append(ent[1]) 82 | -------------------------------------------------------------------------------- /porkchop/commandline.py: -------------------------------------------------------------------------------- 1 | """ 2 | porkchop.commandline 3 | ~~~~~~~~~~~~~~~~~~~~ 4 | 5 | :copyright: (c) 2011-2012 DISQUS. 6 | :license: Apache License 2.0, see LICENSE for more details. 7 | """ 8 | import logging 9 | import socket 10 | from optparse import OptionParser 11 | 12 | from porkchop.plugin import PorkchopPluginHandler 13 | 14 | 15 | def coerce_number(s): 16 | try: 17 | return int(s) 18 | except: 19 | return float(s) 20 | 21 | 22 | def get_logger(name, level=logging.INFO): 23 | logger = logging.getLogger(name) 24 | logger.setLevel(logging.DEBUG) 25 | ch = logging.StreamHandler() 26 | ch.setLevel(level) 27 | formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') 28 | ch.setFormatter(formatter) 29 | logger.addHandler(ch) 30 | 31 | return logger 32 | 33 | 34 | def main(): 35 | from porkchop.server import GetHandler, ThreadedHTTPServer 36 | config_dir = '/etc/porkchop.d' 37 | plugin_dir = '/usr/share/porkchop/plugins' 38 | listen_address = '' 39 | listen_port = 5000 40 | 41 | parser = OptionParser() 42 | parser.add_option('-c', dest='config_dir', 43 | default=config_dir, 44 | help='Load configs from DIR (default: %s)' % config_dir, 45 | metavar='DIR') 46 | parser.add_option('-d', dest='plugin_dir', 47 | default=plugin_dir, 48 | help='Load plugins from DIR (default: %s)' % plugin_dir, 49 | metavar='DIR') 50 | parser.add_option('-s', dest='listen_address', 51 | default=listen_address, 52 | help='Bind to ADDRESS', metavar='ADDRESS') 53 | parser.add_option('-p', type="int", dest='listen_port', 54 | default=listen_port, 55 | help='Bind to PORT (default: %d)' % listen_port, 56 | metavar='PORT') 57 | 58 | (options, args) = parser.parse_args() 59 | 60 | socket.setdefaulttimeout(3) 61 | PorkchopPluginHandler(options.config_dir, options.plugin_dir) 62 | server = ThreadedHTTPServer((options.listen_address, options.listen_port), 63 | GetHandler) 64 | server.serve_forever() 65 | 66 | 67 | def collector(): 68 | import requests 69 | import sys 70 | import time 71 | 72 | from porkchop.backend import Carbon 73 | from porkchop.util import PorkchopUtil 74 | 75 | carbon_host = 'localhost' 76 | carbon_port = 2004 77 | data = {} 78 | porkchop_url = 'http://localhost:5000/' 79 | 80 | interval = 60 81 | prefix = 'porkchop.%s' % socket.gethostname().split('.')[0].replace('.', '_') 82 | 83 | parser = OptionParser() 84 | parser.add_option('--carbon-host', dest='carbon_host', 85 | default=carbon_host, 86 | help='Connect to carbon on HOST (default: %s)' % carbon_host, 87 | metavar='HOST') 88 | parser.add_option('--carbon-port', type='int', dest='carbon_port', 89 | default=carbon_port, 90 | help='Connect to carbon on PORT (default: %d)' % carbon_port, 91 | metavar='PORT') 92 | parser.add_option('--porkchop-url', dest='porkchop_url', 93 | default=porkchop_url, 94 | help='Connect to porkchop on URL (default: %s)' % porkchop_url, 95 | metavar='URL') 96 | parser.add_option('-i', type='int', dest='interval', 97 | default=interval, 98 | help='Fetch data at INTERVAL seconds (default: %d)' % interval, 99 | metavar='INTERVAL') 100 | parser.add_option('-n', dest='noop', 101 | default=False, 102 | help='Don\'t actually send to graphite', 103 | action='store_true') 104 | parser.add_option('-P', dest='prefix', 105 | default=prefix, 106 | help='Graphite prefix (default: %s)' % prefix) 107 | parser.add_option('-v', dest='verbose', 108 | default=False, 109 | help='Verbose logging', 110 | action='store_true') 111 | 112 | (options, args) = parser.parse_args() 113 | 114 | if options.verbose: 115 | logger = get_logger('porkchop-collector', logging.DEBUG) 116 | else: 117 | logger = get_logger('porkchop-collector') 118 | 119 | if not options.noop: 120 | carbon = Carbon(options.carbon_host, options.carbon_port, logger) 121 | 122 | while True: 123 | now = int(time.time()) 124 | try: 125 | logger.debug('Fetching porkchop data from %s', options.porkchop_url) 126 | r = requests.get(options.porkchop_url, 127 | timeout=options.interval, 128 | headers={'x-porkchop-refresh': 'true'}) 129 | r.raise_for_status() 130 | except: 131 | logger.error('Got bad response code from porkchop: %s', sys.exc_info()[1]) 132 | 133 | for line in r.content.strip('\n').splitlines(): 134 | (key, val) = line.lstrip('/').split(' ', 1) 135 | key = PorkchopUtil.char_filter(key) 136 | key = '.'.join([options.prefix, key.replace('/', '.')]) 137 | data.setdefault(key, []) 138 | 139 | try: 140 | data[key].append((now, coerce_number(val))) 141 | 142 | for met in data.keys(): 143 | for datapoint in data[met]: 144 | logger.debug('Sending: %s %s %s', met, datapoint[0], datapoint[1]) 145 | 146 | if not options.noop: 147 | carbon.data = data 148 | carbon.send() 149 | except: 150 | pass 151 | 152 | sleep_time = options.interval - (int(time.time()) - now) 153 | if sleep_time > 0: 154 | logger.info('Sleeping for %d seconds', sleep_time) 155 | time.sleep(sleep_time) 156 | -------------------------------------------------------------------------------- /porkchop/plugin.py: -------------------------------------------------------------------------------- 1 | """ 2 | porkchop.plugin 3 | ~~~~~~~~~~~~~~~ 4 | 5 | :copyright: (c) 2011-2012 DISQUS. 6 | :license: Apache License 2.0, see LICENSE for more details. 7 | """ 8 | from collections import defaultdict 9 | import glob 10 | import imp 11 | import inspect 12 | import os 13 | import sys 14 | import socket 15 | import time 16 | 17 | from porkchop.util import PorkchopUtil 18 | 19 | 20 | class InfiniteDict(defaultdict): 21 | def __init__(self, type=None, *args, **kwargs): 22 | super(InfiniteDict, self).__init__(type or self.__class__) 23 | 24 | 25 | class DotDict(defaultdict): 26 | def __init__(self): 27 | defaultdict.__init__(self, DotDict) 28 | def __setitem__(self, key, value): 29 | keys = key.split('.') 30 | for key in keys[:-1]: 31 | self = self[key] 32 | defaultdict.__setitem__(self, keys[-1], value) 33 | 34 | 35 | class PorkchopPlugin(object): 36 | config_file = None 37 | __delta = None 38 | __prev = None 39 | __cache = None 40 | __data = {} 41 | __lastrefresh = 0 42 | refresh = 60 43 | force_refresh = False 44 | 45 | def __init__(self, handler): 46 | self.handler = handler 47 | 48 | @property 49 | def data(self): 50 | if self.should_refresh(): 51 | self.config = PorkchopUtil.parse_config(self.config_file) 52 | if self.prev_data is None: 53 | self.__class__.__delta = 1 54 | self.prev_data = self.get_data() 55 | time.sleep(1) 56 | else: 57 | self.prev_data = self.__class__.__data 58 | self.data = self.get_data() 59 | 60 | result = self.format_data(self.__class__.__data) 61 | if not result: 62 | return result 63 | result['refreshtime'] = self.__class__.__lastrefresh 64 | return result 65 | 66 | @data.setter 67 | def data(self, value): 68 | now = time.time() 69 | self.__class__.__data = value 70 | self.__class__.__delta = int(now - self.__class__.__lastrefresh) 71 | self.__class__.__lastrefresh = now 72 | self.force_refresh = False 73 | 74 | @property 75 | def delta(self): 76 | return self.__class__.__delta 77 | 78 | @property 79 | def prev_data(self): 80 | return self.__class__.__prev 81 | 82 | @prev_data.setter 83 | def prev_data(self, value): 84 | self.__class__.__prev = value 85 | 86 | def format_data(self, data): 87 | return data 88 | 89 | def gendict(self, type='infinite'): 90 | if type.lower() == 'dot': 91 | return DotDict() 92 | return InfiniteDict() 93 | 94 | def rateof(self, a, b, ival=None): 95 | if ival is None: 96 | ival = self.delta 97 | 98 | a = float(a) 99 | b = float(b) 100 | 101 | try: 102 | return (b - a) / ival if (b - a) != 0 else 0 103 | except ZeroDivisionError: 104 | if a: 105 | return -a 106 | return b 107 | 108 | def should_refresh(self): 109 | if self.force_refresh: 110 | return True 111 | 112 | if self.__class__.__lastrefresh != 0: 113 | return time.time() - self.__class__.__lastrefresh > self.refresh 114 | return True 115 | 116 | def tcp_socket(self, host, port): 117 | sock = socket.socket() 118 | sock.connect((host, port)) 119 | 120 | return sock 121 | 122 | def unix_socket(self, path): 123 | sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) 124 | sock.connect(path) 125 | 126 | return sock 127 | 128 | def log_error(self, *args, **kwargs): 129 | return self.handler.log_error(*args, **kwargs) 130 | 131 | 132 | class PorkchopPluginHandler(object): 133 | plugins = {} 134 | 135 | def __init__(self, config_dir, directory=None): 136 | self.config_dir = config_dir 137 | self.config = PorkchopUtil.parse_config(os.path.join(self.config_dir, 138 | 'porkchop.ini')) 139 | 140 | if directory: 141 | self.__class__.plugins.update(self.load_plugins(directory)) 142 | 143 | self.__class__.plugins.update( 144 | self.load_plugins( 145 | os.path.join(os.path.dirname(__file__), 'plugins') 146 | ) 147 | ) 148 | 149 | def load_plugins(self, directory): 150 | plugins = {} 151 | sys.path.insert(0, directory) 152 | 153 | try: 154 | to_load = [p.strip() for p in self.config['porkchop']['plugins'].split(',')] 155 | except: 156 | to_load = [] 157 | 158 | for infile in glob.glob(os.path.join(directory, '*.py')): 159 | module_name = os.path.splitext(os.path.split(infile)[1])[0] 160 | 161 | if os.path.basename(infile) == '__init__.py': 162 | continue 163 | if to_load and module_name not in to_load: 164 | continue 165 | 166 | try: 167 | module = imp.load_source(module_name, infile) 168 | for namek, klass in inspect.getmembers(module): 169 | if inspect.isclass(klass) \ 170 | and issubclass(klass, PorkchopPlugin) \ 171 | and klass is not PorkchopPlugin: 172 | 173 | if hasattr(klass, '__metric_name__'): 174 | plugin_name = klass.__metric_name__ 175 | else: 176 | plugin_name = module_name 177 | 178 | plugins[plugin_name] = klass 179 | plugins[plugin_name].config_file = os.path.join( 180 | self.config_dir, 181 | '%s.ini' % plugin_name 182 | ) 183 | 184 | # Only one plugin per module. 185 | break 186 | 187 | except ImportError: 188 | print 'Unable to load plugin %r' % infile 189 | import traceback 190 | traceback.print_exc() 191 | 192 | return plugins 193 | -------------------------------------------------------------------------------- /porkchop/server.py: -------------------------------------------------------------------------------- 1 | """ 2 | porkchop.server 3 | ~~~~~~~~~~~~~~~ 4 | 5 | :copyright: (c) 2011-2012 DISQUS. 6 | :license: Apache License 2.0, see LICENSE for more details. 7 | """ 8 | from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer 9 | from SocketServer import ThreadingMixIn 10 | import json 11 | import traceback 12 | import urlparse 13 | 14 | from porkchop.plugin import PorkchopPluginHandler 15 | 16 | 17 | class GetHandler(BaseHTTPRequestHandler): 18 | def format_output(self, fmt, data): 19 | if fmt == 'json': 20 | return json.dumps(data) 21 | else: 22 | return '\n'.join(self.json_path(data)) 23 | 24 | def json_path(self, data): 25 | results = [] 26 | 27 | def path_helper(data, path, results): 28 | for key, val in data.iteritems(): 29 | if isinstance(val, dict): 30 | path_helper(val, '/'.join((path, key)), results) 31 | else: 32 | results.append(('%s %s' % (('/'.join((path, key)))\ 33 | .replace('.', '_'), val))) 34 | 35 | path_helper(data, '', results) 36 | return results 37 | 38 | def do_GET(self): 39 | data = {} 40 | formats = {'json': 'application/json', 'text': 'text/plain'} 41 | request = urlparse.urlparse(self.path) 42 | 43 | try: 44 | (path, fmt) = request.path.split('.') 45 | if fmt not in formats.keys(): 46 | fmt = 'text' 47 | except ValueError: 48 | path = request.path 49 | if self.headers.get('accept', False) == 'application/json': 50 | fmt = 'json' 51 | else: 52 | fmt = 'text' 53 | 54 | if self.headers.get('x-porkchop-refresh', False): 55 | force_refresh = True 56 | else: 57 | force_refresh = False 58 | 59 | module = path.split('/')[1] 60 | 61 | try: 62 | if module: 63 | plugin = PorkchopPluginHandler.plugins[module](self) 64 | plugin.force_refresh = force_refresh 65 | self.log_message('Calling plugin: %s with force=%s' % (module, force_refresh)) 66 | data.update({module: plugin.data}) 67 | else: 68 | for plugin_name, plugin in PorkchopPluginHandler.plugins.iteritems(): 69 | try: 70 | plugin.force_refresh = force_refresh 71 | self.log_message('Calling plugin: %s with force=%s' % (plugin_name, force_refresh)) 72 | # if the plugin has no data, it'll only have one key: 73 | # refreshtime 74 | result = plugin(self).data 75 | if len(result) > 1: 76 | data.update({plugin_name: result}) 77 | except Exception, e: 78 | self.log_error('Error loading plugin: name=%s exception=%s, traceback=%s', plugin_name, e, 79 | traceback.format_exc()) 80 | 81 | if len(data): 82 | self.send_response(200) 83 | self.send_header('Content-Type', formats[fmt]) 84 | self.end_headers() 85 | self.wfile.write(self.format_output(fmt, data) + '\n') 86 | else: 87 | raise Exception('Unable to load any plugins') 88 | except Exception, e: 89 | self.log_error('Error: %s\n%s', e, traceback.format_exc()) 90 | self.send_response(404) 91 | self.send_header('Content-Type', formats[fmt]) 92 | self.end_headers() 93 | self.wfile.write(self.format_output(fmt, {})) 94 | 95 | 96 | class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): 97 | pass 98 | -------------------------------------------------------------------------------- /porkchop/util.py: -------------------------------------------------------------------------------- 1 | """ 2 | porkchop.util 3 | ~~~~~~~~~~~~~ 4 | 5 | :copyright: (c) 2011-2012 DISQUS. 6 | :license: Apache License 2.0, see LICENSE for more details. 7 | """ 8 | import ConfigParser 9 | 10 | 11 | class PorkchopUtil(object): 12 | @classmethod 13 | def parse_config(self, path): 14 | config = {} 15 | cp = ConfigParser.ConfigParser() 16 | cp.read(path) 17 | 18 | for s in cp.sections(): 19 | config.setdefault(s, {}) 20 | for o in cp.options(s): 21 | config[s][o] = cp.get(s, o) 22 | 23 | return config 24 | 25 | 26 | @classmethod 27 | def char_filter(cls, s): 28 | import string 29 | 30 | wanted = string.letters + string.digits + string.punctuation 31 | return "".join(c for c in s if c in wanted and not c == '.') 32 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from setuptools import setup, find_packages 4 | 5 | version = '0.9.1' 6 | 7 | setup(name='porkchop', 8 | version=version, 9 | description='Porkchop is a simple HTTP-based system information server', 10 | long_description='Porkchop is a simple HTTP-based system information server', 11 | classifiers=[ 12 | 'Development Status :: 3 - Alpha', 13 | 'Intended Audience :: System Administrators', 14 | 'License :: OSI Approved :: Apache Software License', 15 | 'Topic :: System :: Networking :: Monitoring' 16 | ], 17 | keywords='', 18 | author='DISQUS', 19 | author_email='opensource@disqus.com', 20 | url='http://github.com/disqus/porkchop', 21 | license='Apache 2.0', 22 | packages=find_packages(), 23 | include_package_data=True, 24 | zip_safe=False, 25 | install_requires=['requests', 'setuptools'], 26 | entry_points={ 27 | 'console_scripts': [ 28 | 'porkchop = porkchop.commandline:main', 29 | 'porkchop-collector = porkchop.commandline:collector' 30 | ], 31 | } 32 | ) 33 | --------------------------------------------------------------------------------