summaryrefslogtreecommitdiff
path: root/src/metrics/newrelic/interface.py
blob: a9db15fd9024aeb25491939fde4d71ac13ea9878 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
import zlib
import sys
import socket
import os
import types
import json
import logging

try:
    import http.client as httplib
except ImportError:
    import httplib

_logger = logging.getLogger(__name__)

# Python 3 compatibility helpers.

PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3

if PY3:
    def b(s):
        return s.encode('latin-1')
else:
    def b(s):
        return s

# Helpers for json encoding and decoding.

def json_encode(obj, **kwargs):
    _kwargs = {}

    if type(b'') is type(''):
        _kwargs['encoding'] = 'latin-1'

    def _encode(o):
        if isinstance(o, bytes):
            return o.decode('latin-1')
        elif isinstance(o, types.GeneratorType):
            return list(o)
        elif hasattr(o, '__iter__'):
            return list(iter(o))
        raise TypeError(repr(o) + ' is not JSON serializable')

    _kwargs['default'] = _encode
    _kwargs['separators'] = (',', ':')

    _kwargs.update(kwargs)

    return json.dumps(obj, **_kwargs)

def json_decode(s, **kwargs):
    return json.loads(s, **kwargs)

# Platform plugin interface.

class Interface(object):

    class NetworkInterfaceException(Exception): pass
    class DiscardDataForRequest(NetworkInterfaceException): pass
    class RetryDataForRequest(NetworkInterfaceException): pass
    class ServerIsUnavailable(RetryDataForRequest): pass

    USER_AGENT = 'ModWsgi-PythonPlugin/%s (Python %s %s)' % (
             '1.0.0', sys.version.split()[0], sys.platform)

    HOST = 'platform-api.newrelic.com'
    URL = '/platform/v1/metrics'

    def __init__(self, license_key):
        self.license_key = license_key

    def send_request(self, payload=()):
        headers = {}
        config = {}

        license_key = self.license_key

        if not self.license_key:
            license_key = 'INVALID LICENSE KEY'

        headers['User-Agent'] = self.USER_AGENT
        headers['Content-Encoding'] = 'identity'
        headers['X-License-Key'] = license_key

        try:
            data = json_encode(payload)

        except Exception as exc:
            _logger.exception('Error encoding data for JSON payload '
                    'with payload of %r.', payload)

            raise Interface.DiscardDataForRequest(str(exc))

        if len(data) > 64*1024:
            headers['Content-Encoding'] = 'deflate'
            level = (len(data) < 2000000) and 1 or 9
            data = zlib.compress(b(data), level)

        try:
            connection = httplib.HTTPSConnection(self.HOST, timeout=30.0)
            connection.request('POST', self.URL, data, headers)
            response = connection.getresponse()
            content = response.read()

        except httplib.HTTPException as exc:
            raise Interface.RetryDataForRequest(str(exc))

        finally:
            connection.close()

        if response.status != 200:
            _logger.debug('Received a non 200 HTTP response from the data '
                    'collector where headers=%r, status=%r and content=%r.',
                    headers, response.status, content)

        if response.status == 400:
            if headers['Content-Encoding'] == 'deflate':
                data = zlib.decompress(data)

            _logger.error('Data collector is indicating that a bad '
                    'request has been submitted for headers of %r and '
                    'payload of %r with response of %r.', headers, data,
                    content)

            raise Interface.DiscardDataForRequest()

        elif response.status == 403:
            _logger.error('Data collector is indicating that the license '
                    'key %r is not valid.', license_key)

            raise Interface.DiscardDataForRequest()

        elif response.status == 413:
            _logger.warning('Data collector is indicating that a request '
                    'was received where the request content size was over '
                    'the maximum allowed size limit. The length of the '
                    'request content was %d.', len(data))

            raise Interface.DiscardDataForRequest()

        elif response.status in  (503, 504):
            _logger.warning('Data collector is unavailable.')

            raise Interface.ServerIsUnavailable()

        elif response.status != 200:
            _logger.warning('An unexpected HTTP response was received '
                    'from the data collector of %r. The payload for '
                    'the request was %r.', respnse.status, payload)

            raise Interface.DiscardDataForRequest()

        try:
            if PY3:
                content = content.decode('UTF-8')

            result = json_decode(content)

        except Exception as exc:
            _logger.exception('Error decoding data for JSON payload '
                    'with payload of %r.', content)

            raise Interface.DiscardDataForRequest(str(exc))

        if 'status' in result:
            return result['status']

        error_message = result['error']

        raise Interface.DiscardDataForRequest(error_message)

    def send_metrics(self, name, guid, version, duration, metrics):
        agent = {}
        agent['host'] = socket.gethostname()
        agent['pid'] = os.getpid()
        agent['version'] = version or '0.0.0.'

        component = {}
        component['name'] = name
        component['guid'] = guid
        component['duration'] = duration
        component['metrics'] = metrics

        payload = {}
        payload['agent'] = agent
        payload['components'] = [component]

        return self.send_request(payload)