We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Mesos master port in mesos_slave.py is hardcoded
https://github.com/DataDog/dd-agent/blob/master/checks.d/mesos_slave.py#L132

Effecting mesos_slave configuration doesn't work if the master port is other than 5050.
Probably should be added in configuration.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `checks.d/mesos_slave.py`
Content:
```
1 """Mesos Slave check
2 
3 Collects metrics from mesos slave node.
4 """
5 # 3rd party
6 import requests
7 
8 # project
9 from checks import AgentCheck, CheckException
10 
11 
12 class MesosSlave(AgentCheck):
13     GAUGE = AgentCheck.gauge
14     MONOTONIC_COUNT = AgentCheck.monotonic_count
15     SERVICE_CHECK_NAME = "mesos_slave.can_connect"
16     service_check_needed = True
17 
18     TASK_STATUS = {
19         'TASK_STARTING'     : AgentCheck.OK,
20         'TASK_RUNNING'      : AgentCheck.OK,
21         'TASK_FINISHED'     : AgentCheck.OK,
22         'TASK_FAILED'       : AgentCheck.CRITICAL,
23         'TASK_KILLED'       : AgentCheck.WARNING,
24         'TASK_LOST'         : AgentCheck.CRITICAL,
25         'TASK_STAGING'      : AgentCheck.OK,
26         'TASK_ERROR'        : AgentCheck.CRITICAL,
27     }
28 
29     TASK_METRICS = {
30         'cpus'                              : ('mesos.state.task.cpu', GAUGE),
31         'mem'                               : ('mesos.state.task.mem', GAUGE),
32         'disk'                              : ('mesos.state.task.disk', GAUGE),
33     }
34 
35     SLAVE_TASKS_METRICS = {
36         'slave/tasks_failed'                : ('mesos.slave.tasks_failed', MONOTONIC_COUNT),
37         'slave/tasks_finished'              : ('mesos.slave.tasks_finished', MONOTONIC_COUNT),
38         'slave/tasks_killed'                : ('mesos.slave.tasks_killed', MONOTONIC_COUNT),
39         'slave/tasks_lost'                  : ('mesos.slave.tasks_lost', MONOTONIC_COUNT),
40         'slave/tasks_running'               : ('mesos.slave.tasks_running', GAUGE),
41         'slave/tasks_staging'               : ('mesos.slave.tasks_staging', GAUGE),
42         'slave/tasks_starting'              : ('mesos.slave.tasks_starting', GAUGE),
43     }
44 
45     SYSTEM_METRICS = {
46         'system/cpus_total'                 : ('mesos.stats.system.cpus_total', GAUGE),
47         'system/load_15min'                 : ('mesos.stats.system.load_15min', GAUGE),
48         'system/load_1min'                  : ('mesos.stats.system.load_1min', GAUGE),
49         'system/load_5min'                  : ('mesos.stats.system.load_5min', GAUGE),
50         'system/mem_free_bytes'             : ('mesos.stats.system.mem_free_bytes', GAUGE),
51         'system/mem_total_bytes'            : ('mesos.stats.system.mem_total_bytes', GAUGE),
52         'slave/registered'                  : ('mesos.stats.registered', GAUGE),
53         'slave/uptime_secs'                 : ('mesos.stats.uptime_secs', GAUGE),
54     }
55 
56     SLAVE_RESOURCE_METRICS = {
57         'slave/cpus_percent'                : ('mesos.slave.cpus_percent', GAUGE),
58         'slave/cpus_total'                  : ('mesos.slave.cpus_total', GAUGE),
59         'slave/cpus_used'                   : ('mesos.slave.cpus_used', GAUGE),
60         'slave/disk_percent'                : ('mesos.slave.disk_percent', GAUGE),
61         'slave/disk_total'                  : ('mesos.slave.disk_total', GAUGE),
62         'slave/disk_used'                   : ('mesos.slave.disk_used', GAUGE),
63         'slave/mem_percent'                 : ('mesos.slave.mem_percent', GAUGE),
64         'slave/mem_total'                   : ('mesos.slave.mem_total', GAUGE),
65         'slave/mem_used'                    : ('mesos.slave.mem_used', GAUGE),
66     }
67 
68     SLAVE_EXECUTORS_METRICS = {
69         'slave/executors_registering'       : ('mesos.slave.executors_registering', GAUGE),
70         'slave/executors_running'           : ('mesos.slave.executors_running', GAUGE),
71         'slave/executors_terminated'        : ('mesos.slave.executors_terminated', GAUGE),
72         'slave/executors_terminating'       : ('mesos.slave.executors_terminating', GAUGE),
73     }
74 
75     STATS_METRICS = {
76         'slave/frameworks_active'           : ('mesos.slave.frameworks_active', GAUGE),
77         'slave/invalid_framework_messages'  : ('mesos.slave.invalid_framework_messages', GAUGE),
78         'slave/invalid_status_updates'      : ('mesos.slave.invalid_status_updates', GAUGE),
79         'slave/recovery_errors'             : ('mesos.slave.recovery_errors', GAUGE),
80         'slave/valid_framework_messages'    : ('mesos.slave.valid_framework_messages', GAUGE),
81         'slave/valid_status_updates'        : ('mesos.slave.valid_status_updates', GAUGE),
82     }
83 
84     def __init__(self, name, init_config, agentConfig, instances=None):
85         AgentCheck.__init__(self, name, init_config, agentConfig, instances)
86         self.cluster_name = None
87 
88     def _get_json(self, url, timeout):
89         tags = ["url:%s" % url]
90         msg = None
91         status = None
92         try:
93             r = requests.get(url, timeout=timeout)
94             if r.status_code != 200:
95                 status = AgentCheck.CRITICAL
96                 msg = "Got %s when hitting %s" % (r.status_code, url)
97             else:
98                 status = AgentCheck.OK
99                 msg = "Mesos master instance detected at %s " % url
100         except requests.exceptions.Timeout as e:
101             # If there's a timeout
102             msg = "%s seconds timeout when hitting %s" % (timeout, url)
103             status = AgentCheck.CRITICAL
104         except Exception as e:
105             msg = str(e)
106             status = AgentCheck.CRITICAL
107         finally:
108             if self.service_check_needed:
109                 self.service_check(self.SERVICE_CHECK_NAME, status, tags=tags, message=msg)
110                 self.service_check_needed = False
111             if status is AgentCheck.CRITICAL:
112                 raise CheckException("Cannot connect to mesos, please check your configuration.")
113 
114         return r.json()
115 
116     def _get_state(self, url, timeout):
117         return self._get_json(url + '/state.json', timeout)
118 
119     def _get_stats(self, url, timeout):
120         if self.version >= [0, 22, 0]:
121             endpoint = '/metrics/snapshot'
122         else:
123             endpoint = '/stats.json'
124         return self._get_json(url + endpoint, timeout)
125 
126     def _get_constant_attributes(self, url, timeout):
127         state_metrics = None
128         if self.cluster_name is None:
129             state_metrics = self._get_state(url, timeout)
130             if state_metrics is not None:
131                 self.version = map(int, state_metrics['version'].split('.'))
132                 master_state = self._get_state('http://' + state_metrics['master_hostname'] + ':5050', timeout)
133                 if master_state is not None:
134                     self.cluster_name = master_state.get('cluster')
135 
136         return state_metrics
137 
138     def check(self, instance):
139         if 'url' not in instance:
140             raise Exception('Mesos instance missing "url" value.')
141 
142         url = instance['url']
143         instance_tags = instance.get('tags', [])
144         tasks = instance.get('tasks', [])
145         default_timeout = self.init_config.get('default_timeout', 5)
146         timeout = float(instance.get('timeout', default_timeout))
147 
148         state_metrics = self._get_constant_attributes(url, timeout)
149         tags = None
150 
151         if state_metrics is None:
152             state_metrics = self._get_state(url, timeout)
153         if state_metrics:
154             tags = [
155                 'mesos_pid:{0}'.format(state_metrics['pid']),
156                 'mesos_node:slave',
157             ]
158             if self.cluster_name:
159                 tags.append('mesos_cluster:{0}'.format(self.cluster_name))
160 
161             tags += instance_tags
162 
163             for task in tasks:
164                 for framework in state_metrics['frameworks']:
165                     for executor in framework['executors']:
166                         for t in executor['tasks']:
167                             if task.lower() in t['name'].lower() and t['slave_id'] == state_metrics['id']:
168                                 task_tags = ['task_name:' + t['name']] + tags
169                                 self.service_check(t['name'] + '.ok', self.TASK_STATUS[t['state']], tags=task_tags)
170                                 for key_name, (metric_name, metric_func) in self.TASK_METRICS.iteritems():
171                                     metric_func(self, metric_name, t['resources'][key_name], tags=task_tags)
172 
173         stats_metrics = self._get_stats(url, timeout)
174         if stats_metrics:
175             tags = tags if tags else instance_tags
176             metrics = [self.SLAVE_TASKS_METRICS, self.SYSTEM_METRICS, self.SLAVE_RESOURCE_METRICS,
177                       self.SLAVE_EXECUTORS_METRICS, self.STATS_METRICS]
178             for m in metrics:
179                 for key_name, (metric_name, metric_func) in m.iteritems():
180                     metric_func(self, metric_name, stats_metrics[key_name], tags=tags)
181 
182         self.service_check_needed = True
183
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/checks.d/mesos_slave.py b/checks.d/mesos_slave.py
--- a/checks.d/mesos_slave.py
+++ b/checks.d/mesos_slave.py
@@ -8,6 +8,7 @@
 # project
 from checks import AgentCheck, CheckException
 
+DEFAULT_MASTER_PORT = 5050
 
 class MesosSlave(AgentCheck):
     GAUGE = AgentCheck.gauge
@@ -123,13 +124,16 @@
             endpoint = '/stats.json'
         return self._get_json(url + endpoint, timeout)
 
-    def _get_constant_attributes(self, url, timeout):
+    def _get_constant_attributes(self, url, timeout, master_port):
         state_metrics = None
         if self.cluster_name is None:
             state_metrics = self._get_state(url, timeout)
             if state_metrics is not None:
                 self.version = map(int, state_metrics['version'].split('.'))
-                master_state = self._get_state('http://' + state_metrics['master_hostname'] + ':5050', timeout)
+                master_state = self._get_state(
+                    'http://{0}:{1}'.format(state_metrics['master_hostname'], master_port),
+                    timeout
+                )
                 if master_state is not None:
                     self.cluster_name = master_state.get('cluster')
 
@@ -144,8 +148,9 @@
         tasks = instance.get('tasks', [])
         default_timeout = self.init_config.get('default_timeout', 5)
         timeout = float(instance.get('timeout', default_timeout))
+        master_port = instance.get("master_port", DEFAULT_MASTER_PORT)
 
-        state_metrics = self._get_constant_attributes(url, timeout)
+        state_metrics = self._get_constant_attributes(url, timeout, master_port)
         tags = None
 
         if state_metrics is None:

{"golden_diff": "diff --git a/checks.d/mesos_slave.py b/checks.d/mesos_slave.py\n--- a/checks.d/mesos_slave.py\n+++ b/checks.d/mesos_slave.py\n@@ -8,6 +8,7 @@\n # project\n from checks import AgentCheck, CheckException\n \n+DEFAULT_MASTER_PORT = 5050\n \n class MesosSlave(AgentCheck):\n     GAUGE = AgentCheck.gauge\n@@ -123,13 +124,16 @@\n             endpoint = '/stats.json'\n         return self._get_json(url + endpoint, timeout)\n \n-    def _get_constant_attributes(self, url, timeout):\n+    def _get_constant_attributes(self, url, timeout, master_port):\n         state_metrics = None\n         if self.cluster_name is None:\n             state_metrics = self._get_state(url, timeout)\n             if state_metrics is not None:\n                 self.version = map(int, state_metrics['version'].split('.'))\n-                master_state = self._get_state('http://' + state_metrics['master_hostname'] + ':5050', timeout)\n+                master_state = self._get_state(\n+                    'http://{0}:{1}'.format(state_metrics['master_hostname'], master_port),\n+                    timeout\n+                )\n                 if master_state is not None:\n                     self.cluster_name = master_state.get('cluster')\n \n@@ -144,8 +148,9 @@\n         tasks = instance.get('tasks', [])\n         default_timeout = self.init_config.get('default_timeout', 5)\n         timeout = float(instance.get('timeout', default_timeout))\n+        master_port = instance.get(\"master_port\", DEFAULT_MASTER_PORT)\n \n-        state_metrics = self._get_constant_attributes(url, timeout)\n+        state_metrics = self._get_constant_attributes(url, timeout, master_port)\n         tags = None\n \n         if state_metrics is None:\n", "issue": "Mesos master port in mesos_slave.py is hardcoded\nhttps://github.com/DataDog/dd-agent/blob/master/checks.d/mesos_slave.py#L132\n\nEffecting mesos_slave configuration doesn't work if the master port is other than 5050.\nProbably should be added in configuration.\n\n", "before_files": [{"content": "\"\"\"Mesos Slave check\n\nCollects metrics from mesos slave node.\n\"\"\"\n# 3rd party\nimport requests\n\n# project\nfrom checks import AgentCheck, CheckException\n\n\nclass MesosSlave(AgentCheck):\n    GAUGE = AgentCheck.gauge\n    MONOTONIC_COUNT = AgentCheck.monotonic_count\n    SERVICE_CHECK_NAME = \"mesos_slave.can_connect\"\n    service_check_needed = True\n\n    TASK_STATUS = {\n        'TASK_STARTING'     : AgentCheck.OK,\n        'TASK_RUNNING'      : AgentCheck.OK,\n        'TASK_FINISHED'     : AgentCheck.OK,\n        'TASK_FAILED'       : AgentCheck.CRITICAL,\n        'TASK_KILLED'       : AgentCheck.WARNING,\n        'TASK_LOST'         : AgentCheck.CRITICAL,\n        'TASK_STAGING'      : AgentCheck.OK,\n        'TASK_ERROR'        : AgentCheck.CRITICAL,\n    }\n\n    TASK_METRICS = {\n        'cpus'                              : ('mesos.state.task.cpu', GAUGE),\n        'mem'                               : ('mesos.state.task.mem', GAUGE),\n        'disk'                              : ('mesos.state.task.disk', GAUGE),\n    }\n\n    SLAVE_TASKS_METRICS = {\n        'slave/tasks_failed'                : ('mesos.slave.tasks_failed', MONOTONIC_COUNT),\n        'slave/tasks_finished'              : ('mesos.slave.tasks_finished', MONOTONIC_COUNT),\n        'slave/tasks_killed'                : ('mesos.slave.tasks_killed', MONOTONIC_COUNT),\n        'slave/tasks_lost'                  : ('mesos.slave.tasks_lost', MONOTONIC_COUNT),\n        'slave/tasks_running'               : ('mesos.slave.tasks_running', GAUGE),\n        'slave/tasks_staging'               : ('mesos.slave.tasks_staging', GAUGE),\n        'slave/tasks_starting'              : ('mesos.slave.tasks_starting', GAUGE),\n    }\n\n    SYSTEM_METRICS = {\n        'system/cpus_total'                 : ('mesos.stats.system.cpus_total', GAUGE),\n        'system/load_15min'                 : ('mesos.stats.system.load_15min', GAUGE),\n        'system/load_1min'                  : ('mesos.stats.system.load_1min', GAUGE),\n        'system/load_5min'                  : ('mesos.stats.system.load_5min', GAUGE),\n        'system/mem_free_bytes'             : ('mesos.stats.system.mem_free_bytes', GAUGE),\n        'system/mem_total_bytes'            : ('mesos.stats.system.mem_total_bytes', GAUGE),\n        'slave/registered'                  : ('mesos.stats.registered', GAUGE),\n        'slave/uptime_secs'                 : ('mesos.stats.uptime_secs', GAUGE),\n    }\n\n    SLAVE_RESOURCE_METRICS = {\n        'slave/cpus_percent'                : ('mesos.slave.cpus_percent', GAUGE),\n        'slave/cpus_total'                  : ('mesos.slave.cpus_total', GAUGE),\n        'slave/cpus_used'                   : ('mesos.slave.cpus_used', GAUGE),\n        'slave/disk_percent'                : ('mesos.slave.disk_percent', GAUGE),\n        'slave/disk_total'                  : ('mesos.slave.disk_total', GAUGE),\n        'slave/disk_used'                   : ('mesos.slave.disk_used', GAUGE),\n        'slave/mem_percent'                 : ('mesos.slave.mem_percent', GAUGE),\n        'slave/mem_total'                   : ('mesos.slave.mem_total', GAUGE),\n        'slave/mem_used'                    : ('mesos.slave.mem_used', GAUGE),\n    }\n\n    SLAVE_EXECUTORS_METRICS = {\n        'slave/executors_registering'       : ('mesos.slave.executors_registering', GAUGE),\n        'slave/executors_running'           : ('mesos.slave.executors_running', GAUGE),\n        'slave/executors_terminated'        : ('mesos.slave.executors_terminated', GAUGE),\n        'slave/executors_terminating'       : ('mesos.slave.executors_terminating', GAUGE),\n    }\n\n    STATS_METRICS = {\n        'slave/frameworks_active'           : ('mesos.slave.frameworks_active', GAUGE),\n        'slave/invalid_framework_messages'  : ('mesos.slave.invalid_framework_messages', GAUGE),\n        'slave/invalid_status_updates'      : ('mesos.slave.invalid_status_updates', GAUGE),\n        'slave/recovery_errors'             : ('mesos.slave.recovery_errors', GAUGE),\n        'slave/valid_framework_messages'    : ('mesos.slave.valid_framework_messages', GAUGE),\n        'slave/valid_status_updates'        : ('mesos.slave.valid_status_updates', GAUGE),\n    }\n\n    def __init__(self, name, init_config, agentConfig, instances=None):\n        AgentCheck.__init__(self, name, init_config, agentConfig, instances)\n        self.cluster_name = None\n\n    def _get_json(self, url, timeout):\n        tags = [\"url:%s\" % url]\n        msg = None\n        status = None\n        try:\n            r = requests.get(url, timeout=timeout)\n            if r.status_code != 200:\n                status = AgentCheck.CRITICAL\n                msg = \"Got %s when hitting %s\" % (r.status_code, url)\n            else:\n                status = AgentCheck.OK\n                msg = \"Mesos master instance detected at %s \" % url\n        except requests.exceptions.Timeout as e:\n            # If there's a timeout\n            msg = \"%s seconds timeout when hitting %s\" % (timeout, url)\n            status = AgentCheck.CRITICAL\n        except Exception as e:\n            msg = str(e)\n            status = AgentCheck.CRITICAL\n        finally:\n            if self.service_check_needed:\n                self.service_check(self.SERVICE_CHECK_NAME, status, tags=tags, message=msg)\n                self.service_check_needed = False\n            if status is AgentCheck.CRITICAL:\n                raise CheckException(\"Cannot connect to mesos, please check your configuration.\")\n\n        return r.json()\n\n    def _get_state(self, url, timeout):\n        return self._get_json(url + '/state.json', timeout)\n\n    def _get_stats(self, url, timeout):\n        if self.version >= [0, 22, 0]:\n            endpoint = '/metrics/snapshot'\n        else:\n            endpoint = '/stats.json'\n        return self._get_json(url + endpoint, timeout)\n\n    def _get_constant_attributes(self, url, timeout):\n        state_metrics = None\n        if self.cluster_name is None:\n            state_metrics = self._get_state(url, timeout)\n            if state_metrics is not None:\n                self.version = map(int, state_metrics['version'].split('.'))\n                master_state = self._get_state('http://' + state_metrics['master_hostname'] + ':5050', timeout)\n                if master_state is not None:\n                    self.cluster_name = master_state.get('cluster')\n\n        return state_metrics\n\n    def check(self, instance):\n        if 'url' not in instance:\n            raise Exception('Mesos instance missing \"url\" value.')\n\n        url = instance['url']\n        instance_tags = instance.get('tags', [])\n        tasks = instance.get('tasks', [])\n        default_timeout = self.init_config.get('default_timeout', 5)\n        timeout = float(instance.get('timeout', default_timeout))\n\n        state_metrics = self._get_constant_attributes(url, timeout)\n        tags = None\n\n        if state_metrics is None:\n            state_metrics = self._get_state(url, timeout)\n        if state_metrics:\n            tags = [\n                'mesos_pid:{0}'.format(state_metrics['pid']),\n                'mesos_node:slave',\n            ]\n            if self.cluster_name:\n                tags.append('mesos_cluster:{0}'.format(self.cluster_name))\n\n            tags += instance_tags\n\n            for task in tasks:\n                for framework in state_metrics['frameworks']:\n                    for executor in framework['executors']:\n                        for t in executor['tasks']:\n                            if task.lower() in t['name'].lower() and t['slave_id'] == state_metrics['id']:\n                                task_tags = ['task_name:' + t['name']] + tags\n                                self.service_check(t['name'] + '.ok', self.TASK_STATUS[t['state']], tags=task_tags)\n                                for key_name, (metric_name, metric_func) in self.TASK_METRICS.iteritems():\n                                    metric_func(self, metric_name, t['resources'][key_name], tags=task_tags)\n\n        stats_metrics = self._get_stats(url, timeout)\n        if stats_metrics:\n            tags = tags if tags else instance_tags\n            metrics = [self.SLAVE_TASKS_METRICS, self.SYSTEM_METRICS, self.SLAVE_RESOURCE_METRICS,\n                      self.SLAVE_EXECUTORS_METRICS, self.STATS_METRICS]\n            for m in metrics:\n                for key_name, (metric_name, metric_func) in m.iteritems():\n                    metric_func(self, metric_name, stats_metrics[key_name], tags=tags)\n\n        self.service_check_needed = True\n", "path": "checks.d/mesos_slave.py"}], "after_files": [{"content": "\"\"\"Mesos Slave check\n\nCollects metrics from mesos slave node.\n\"\"\"\n# 3rd party\nimport requests\n\n# project\nfrom checks import AgentCheck, CheckException\n\nDEFAULT_MASTER_PORT = 5050\n\nclass MesosSlave(AgentCheck):\n    GAUGE = AgentCheck.gauge\n    MONOTONIC_COUNT = AgentCheck.monotonic_count\n    SERVICE_CHECK_NAME = \"mesos_slave.can_connect\"\n    service_check_needed = True\n\n    TASK_STATUS = {\n        'TASK_STARTING'     : AgentCheck.OK,\n        'TASK_RUNNING'      : AgentCheck.OK,\n        'TASK_FINISHED'     : AgentCheck.OK,\n        'TASK_FAILED'       : AgentCheck.CRITICAL,\n        'TASK_KILLED'       : AgentCheck.WARNING,\n        'TASK_LOST'         : AgentCheck.CRITICAL,\n        'TASK_STAGING'      : AgentCheck.OK,\n        'TASK_ERROR'        : AgentCheck.CRITICAL,\n    }\n\n    TASK_METRICS = {\n        'cpus'                              : ('mesos.state.task.cpu', GAUGE),\n        'mem'                               : ('mesos.state.task.mem', GAUGE),\n        'disk'                              : ('mesos.state.task.disk', GAUGE),\n    }\n\n    SLAVE_TASKS_METRICS = {\n        'slave/tasks_failed'                : ('mesos.slave.tasks_failed', MONOTONIC_COUNT),\n        'slave/tasks_finished'              : ('mesos.slave.tasks_finished', MONOTONIC_COUNT),\n        'slave/tasks_killed'                : ('mesos.slave.tasks_killed', MONOTONIC_COUNT),\n        'slave/tasks_lost'                  : ('mesos.slave.tasks_lost', MONOTONIC_COUNT),\n        'slave/tasks_running'               : ('mesos.slave.tasks_running', GAUGE),\n        'slave/tasks_staging'               : ('mesos.slave.tasks_staging', GAUGE),\n        'slave/tasks_starting'              : ('mesos.slave.tasks_starting', GAUGE),\n    }\n\n    SYSTEM_METRICS = {\n        'system/cpus_total'                 : ('mesos.stats.system.cpus_total', GAUGE),\n        'system/load_15min'                 : ('mesos.stats.system.load_15min', GAUGE),\n        'system/load_1min'                  : ('mesos.stats.system.load_1min', GAUGE),\n        'system/load_5min'                  : ('mesos.stats.system.load_5min', GAUGE),\n        'system/mem_free_bytes'             : ('mesos.stats.system.mem_free_bytes', GAUGE),\n        'system/mem_total_bytes'            : ('mesos.stats.system.mem_total_bytes', GAUGE),\n        'slave/registered'                  : ('mesos.stats.registered', GAUGE),\n        'slave/uptime_secs'                 : ('mesos.stats.uptime_secs', GAUGE),\n    }\n\n    SLAVE_RESOURCE_METRICS = {\n        'slave/cpus_percent'                : ('mesos.slave.cpus_percent', GAUGE),\n        'slave/cpus_total'                  : ('mesos.slave.cpus_total', GAUGE),\n        'slave/cpus_used'                   : ('mesos.slave.cpus_used', GAUGE),\n        'slave/disk_percent'                : ('mesos.slave.disk_percent', GAUGE),\n        'slave/disk_total'                  : ('mesos.slave.disk_total', GAUGE),\n        'slave/disk_used'                   : ('mesos.slave.disk_used', GAUGE),\n        'slave/mem_percent'                 : ('mesos.slave.mem_percent', GAUGE),\n        'slave/mem_total'                   : ('mesos.slave.mem_total', GAUGE),\n        'slave/mem_used'                    : ('mesos.slave.mem_used', GAUGE),\n    }\n\n    SLAVE_EXECUTORS_METRICS = {\n        'slave/executors_registering'       : ('mesos.slave.executors_registering', GAUGE),\n        'slave/executors_running'           : ('mesos.slave.executors_running', GAUGE),\n        'slave/executors_terminated'        : ('mesos.slave.executors_terminated', GAUGE),\n        'slave/executors_terminating'       : ('mesos.slave.executors_terminating', GAUGE),\n    }\n\n    STATS_METRICS = {\n        'slave/frameworks_active'           : ('mesos.slave.frameworks_active', GAUGE),\n        'slave/invalid_framework_messages'  : ('mesos.slave.invalid_framework_messages', GAUGE),\n        'slave/invalid_status_updates'      : ('mesos.slave.invalid_status_updates', GAUGE),\n        'slave/recovery_errors'             : ('mesos.slave.recovery_errors', GAUGE),\n        'slave/valid_framework_messages'    : ('mesos.slave.valid_framework_messages', GAUGE),\n        'slave/valid_status_updates'        : ('mesos.slave.valid_status_updates', GAUGE),\n    }\n\n    def __init__(self, name, init_config, agentConfig, instances=None):\n        AgentCheck.__init__(self, name, init_config, agentConfig, instances)\n        self.cluster_name = None\n\n    def _get_json(self, url, timeout):\n        tags = [\"url:%s\" % url]\n        msg = None\n        status = None\n        try:\n            r = requests.get(url, timeout=timeout)\n            if r.status_code != 200:\n                status = AgentCheck.CRITICAL\n                msg = \"Got %s when hitting %s\" % (r.status_code, url)\n            else:\n                status = AgentCheck.OK\n                msg = \"Mesos master instance detected at %s \" % url\n        except requests.exceptions.Timeout as e:\n            # If there's a timeout\n            msg = \"%s seconds timeout when hitting %s\" % (timeout, url)\n            status = AgentCheck.CRITICAL\n        except Exception as e:\n            msg = str(e)\n            status = AgentCheck.CRITICAL\n        finally:\n            if self.service_check_needed:\n                self.service_check(self.SERVICE_CHECK_NAME, status, tags=tags, message=msg)\n                self.service_check_needed = False\n            if status is AgentCheck.CRITICAL:\n                raise CheckException(\"Cannot connect to mesos, please check your configuration.\")\n\n        return r.json()\n\n    def _get_state(self, url, timeout):\n        return self._get_json(url + '/state.json', timeout)\n\n    def _get_stats(self, url, timeout):\n        if self.version >= [0, 22, 0]:\n            endpoint = '/metrics/snapshot'\n        else:\n            endpoint = '/stats.json'\n        return self._get_json(url + endpoint, timeout)\n\n    def _get_constant_attributes(self, url, timeout, master_port):\n        state_metrics = None\n        if self.cluster_name is None:\n            state_metrics = self._get_state(url, timeout)\n            if state_metrics is not None:\n                self.version = map(int, state_metrics['version'].split('.'))\n                master_state = self._get_state(\n                    'http://{0}:{1}'.format(state_metrics['master_hostname'], master_port),\n                    timeout\n                )\n                if master_state is not None:\n                    self.cluster_name = master_state.get('cluster')\n\n        return state_metrics\n\n    def check(self, instance):\n        if 'url' not in instance:\n            raise Exception('Mesos instance missing \"url\" value.')\n\n        url = instance['url']\n        instance_tags = instance.get('tags', [])\n        tasks = instance.get('tasks', [])\n        default_timeout = self.init_config.get('default_timeout', 5)\n        timeout = float(instance.get('timeout', default_timeout))\n        master_port = instance.get(\"master_port\", DEFAULT_MASTER_PORT)\n\n        state_metrics = self._get_constant_attributes(url, timeout, master_port)\n        tags = None\n\n        if state_metrics is None:\n            state_metrics = self._get_state(url, timeout)\n        if state_metrics:\n            tags = [\n                'mesos_pid:{0}'.format(state_metrics['pid']),\n                'mesos_node:slave',\n            ]\n            if self.cluster_name:\n                tags.append('mesos_cluster:{0}'.format(self.cluster_name))\n\n            tags += instance_tags\n\n            for task in tasks:\n                for framework in state_metrics['frameworks']:\n                    for executor in framework['executors']:\n                        for t in executor['tasks']:\n                            if task.lower() in t['name'].lower() and t['slave_id'] == state_metrics['id']:\n                                task_tags = ['task_name:' + t['name']] + tags\n                                self.service_check(t['name'] + '.ok', self.TASK_STATUS[t['state']], tags=task_tags)\n                                for key_name, (metric_name, metric_func) in self.TASK_METRICS.iteritems():\n                                    metric_func(self, metric_name, t['resources'][key_name], tags=task_tags)\n\n        stats_metrics = self._get_stats(url, timeout)\n        if stats_metrics:\n            tags = tags if tags else instance_tags\n            metrics = [self.SLAVE_TASKS_METRICS, self.SYSTEM_METRICS, self.SLAVE_RESOURCE_METRICS,\n                      self.SLAVE_EXECUTORS_METRICS, self.STATS_METRICS]\n            for m in metrics:\n                for key_name, (metric_name, metric_func) in m.iteritems():\n                    metric_func(self, metric_name, stats_metrics[key_name], tags=tags)\n\n        self.service_check_needed = True\n", "path": "checks.d/mesos_slave.py"}]}