We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
apache check doesn't support basic auth
If I want basic auth, I'd assume that all I have to do is make my config look like:

```
apache_status_url: http://user:pass@127.0.0.1:80/server-status?auto
```

But actually that just doesn't work. We need to do some special incantations to make `urllib2` do basic auth.


--- 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/apache.py`
Content:
```
1 import urllib2
2 
3 from util import headers
4 from checks import AgentCheck
5 
6 class Apache(AgentCheck):
7     """Tracks basic connection/requests/workers metrics
8 
9     See http://httpd.apache.org/docs/2.2/mod/mod_status.html for more details
10     """
11     GAUGES = {
12         'IdleWorkers': 'apache.performance.idle_workers',
13         'BusyWorkers': 'apache.performance.busy_workers',
14         'CPULoad': 'apache.performance.cpu_load',
15         'Uptime': 'apache.performance.uptime',
16         'Total kBytes': 'apache.net.bytes',
17         'Total Accesses': 'apache.net.hits',
18     }
19 
20     RATES = {
21         'Total kBytes': 'apache.net.bytes_per_s',
22         'Total Accesses': 'apache.net.request_per_s'
23     }
24 
25     def __init__(self, name, init_config, agentConfig, instances=None):
26         AgentCheck.__init__(self, name, init_config, agentConfig, instances)
27         self.assumed_url = {}
28 
29     def check(self, instance):
30         if 'apache_status_url' not in instance:
31             raise Exception("Missing 'apache_status_url' in Apache config")
32 
33         url = self.assumed_url.get(instance['apache_status_url'], instance['apache_status_url'])
34 
35         tags = instance.get('tags', [])
36         req = urllib2.Request(url, None,
37             headers(self.agentConfig))
38         request = urllib2.urlopen(req)
39         response = request.read()
40 
41         metric_count = 0
42         # Loop through and extract the numerical values
43         for line in response.split('\n'):
44             values = line.split(': ')
45             if len(values) == 2: # match
46                 metric, value = values
47                 try:
48                     value = float(value)
49                 except ValueError:
50                     continue
51 
52                 # Special case: kBytes => bytes
53                 if metric == 'Total kBytes':
54                     value = value * 1024
55 
56                 # Send metric as a gauge, if applicable
57                 if metric in self.GAUGES:
58                     metric_count += 1
59                     metric_name = self.GAUGES[metric]
60                     self.gauge(metric_name, value, tags=tags)
61 
62                 # Send metric as a rate, if applicable
63                 if metric in self.RATES:
64                     metric_count += 1
65                     metric_name = self.RATES[metric]
66                     self.rate(metric_name, value, tags=tags)
67 
68         if metric_count == 0:
69             if self.assumed_url.get(instance['apache_status_url'], None) is None and url[-5:] != '?auto':
70                 self.assumed_url[instance['apache_status_url']]= '%s?auto' % url
71                 self.warning("Assuming url was not correct. Trying to add ?auto suffix to the url")
72                 self.check(instance)
73             else:
74                 raise Exception("No metrics were fetched for this instance. Make sure that %s is the proper url." % instance['apache_status_url'])
75 
76 
77     @staticmethod
78     def parse_agent_config(agentConfig):
79         if not agentConfig.get('apache_status_url'):
80             return False
81 
82         return {
83             'instances': [{'apache_status_url': agentConfig.get('apache_status_url')}]
84         }
85
```
--- 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/apache.py b/checks.d/apache.py
--- a/checks.d/apache.py
+++ b/checks.d/apache.py
@@ -1,4 +1,5 @@
 import urllib2
+import base64
 
 from util import headers
 from checks import AgentCheck
@@ -35,6 +36,10 @@
         tags = instance.get('tags', [])
         req = urllib2.Request(url, None,
             headers(self.agentConfig))
+        if 'apache_user' in instance and 'apache_password' in instance:
+            auth_str = '%s:%s' % (instance['apache_user'], instance['apache_password'])
+            encoded_auth_str = base64.encodestring(auth_str)
+            req.add_header("Authorization", "Basic %s" % encoded_auth_str)
         request = urllib2.urlopen(req)
         response = request.read()

{"golden_diff": "diff --git a/checks.d/apache.py b/checks.d/apache.py\n--- a/checks.d/apache.py\n+++ b/checks.d/apache.py\n@@ -1,4 +1,5 @@\n import urllib2\n+import base64\n \n from util import headers\n from checks import AgentCheck\n@@ -35,6 +36,10 @@\n         tags = instance.get('tags', [])\n         req = urllib2.Request(url, None,\n             headers(self.agentConfig))\n+        if 'apache_user' in instance and 'apache_password' in instance:\n+            auth_str = '%s:%s' % (instance['apache_user'], instance['apache_password'])\n+            encoded_auth_str = base64.encodestring(auth_str)\n+            req.add_header(\"Authorization\", \"Basic %s\" % encoded_auth_str)\n         request = urllib2.urlopen(req)\n         response = request.read()\n", "issue": "apache check doesn't support basic auth\nIf I want basic auth, I'd assume that all I have to do is make my config look like:\n\n```\napache_status_url: http://user:pass@127.0.0.1:80/server-status?auto\n```\n\nBut actually that just doesn't work. We need to do some special incantations to make `urllib2` do basic auth.\n\n", "before_files": [{"content": "import urllib2\n\nfrom util import headers\nfrom checks import AgentCheck\n\nclass Apache(AgentCheck):\n    \"\"\"Tracks basic connection/requests/workers metrics\n\n    See http://httpd.apache.org/docs/2.2/mod/mod_status.html for more details\n    \"\"\"\n    GAUGES = {\n        'IdleWorkers': 'apache.performance.idle_workers',\n        'BusyWorkers': 'apache.performance.busy_workers',\n        'CPULoad': 'apache.performance.cpu_load',\n        'Uptime': 'apache.performance.uptime',\n        'Total kBytes': 'apache.net.bytes',\n        'Total Accesses': 'apache.net.hits',\n    }\n\n    RATES = {\n        'Total kBytes': 'apache.net.bytes_per_s',\n        'Total Accesses': 'apache.net.request_per_s'\n    }\n\n    def __init__(self, name, init_config, agentConfig, instances=None):\n        AgentCheck.__init__(self, name, init_config, agentConfig, instances)\n        self.assumed_url = {}\n\n    def check(self, instance):\n        if 'apache_status_url' not in instance:\n            raise Exception(\"Missing 'apache_status_url' in Apache config\")\n\n        url = self.assumed_url.get(instance['apache_status_url'], instance['apache_status_url'])\n\n        tags = instance.get('tags', [])\n        req = urllib2.Request(url, None,\n            headers(self.agentConfig))\n        request = urllib2.urlopen(req)\n        response = request.read()\n\n        metric_count = 0\n        # Loop through and extract the numerical values\n        for line in response.split('\\n'):\n            values = line.split(': ')\n            if len(values) == 2: # match\n                metric, value = values\n                try:\n                    value = float(value)\n                except ValueError:\n                    continue\n\n                # Special case: kBytes => bytes\n                if metric == 'Total kBytes':\n                    value = value * 1024\n\n                # Send metric as a gauge, if applicable\n                if metric in self.GAUGES:\n                    metric_count += 1\n                    metric_name = self.GAUGES[metric]\n                    self.gauge(metric_name, value, tags=tags)\n\n                # Send metric as a rate, if applicable\n                if metric in self.RATES:\n                    metric_count += 1\n                    metric_name = self.RATES[metric]\n                    self.rate(metric_name, value, tags=tags)\n\n        if metric_count == 0:\n            if self.assumed_url.get(instance['apache_status_url'], None) is None and url[-5:] != '?auto':\n                self.assumed_url[instance['apache_status_url']]= '%s?auto' % url\n                self.warning(\"Assuming url was not correct. Trying to add ?auto suffix to the url\")\n                self.check(instance)\n            else:\n                raise Exception(\"No metrics were fetched for this instance. Make sure that %s is the proper url.\" % instance['apache_status_url'])\n\n\n    @staticmethod\n    def parse_agent_config(agentConfig):\n        if not agentConfig.get('apache_status_url'):\n            return False\n\n        return {\n            'instances': [{'apache_status_url': agentConfig.get('apache_status_url')}]\n        }\n", "path": "checks.d/apache.py"}], "after_files": [{"content": "import urllib2\nimport base64\n\nfrom util import headers\nfrom checks import AgentCheck\n\nclass Apache(AgentCheck):\n    \"\"\"Tracks basic connection/requests/workers metrics\n\n    See http://httpd.apache.org/docs/2.2/mod/mod_status.html for more details\n    \"\"\"\n    GAUGES = {\n        'IdleWorkers': 'apache.performance.idle_workers',\n        'BusyWorkers': 'apache.performance.busy_workers',\n        'CPULoad': 'apache.performance.cpu_load',\n        'Uptime': 'apache.performance.uptime',\n        'Total kBytes': 'apache.net.bytes',\n        'Total Accesses': 'apache.net.hits',\n    }\n\n    RATES = {\n        'Total kBytes': 'apache.net.bytes_per_s',\n        'Total Accesses': 'apache.net.request_per_s'\n    }\n\n    def __init__(self, name, init_config, agentConfig, instances=None):\n        AgentCheck.__init__(self, name, init_config, agentConfig, instances)\n        self.assumed_url = {}\n\n    def check(self, instance):\n        if 'apache_status_url' not in instance:\n            raise Exception(\"Missing 'apache_status_url' in Apache config\")\n\n        url = self.assumed_url.get(instance['apache_status_url'], instance['apache_status_url'])\n\n        tags = instance.get('tags', [])\n        req = urllib2.Request(url, None,\n            headers(self.agentConfig))\n        if 'apache_user' in instance and 'apache_password' in instance:\n            auth_str = '%s:%s' % (instance['apache_user'], instance['apache_password'])\n            encoded_auth_str = base64.encodestring(auth_str)\n            req.add_header(\"Authorization\", \"Basic %s\" % encoded_auth_str)\n        request = urllib2.urlopen(req)\n        response = request.read()\n\n        metric_count = 0\n        # Loop through and extract the numerical values\n        for line in response.split('\\n'):\n            values = line.split(': ')\n            if len(values) == 2: # match\n                metric, value = values\n                try:\n                    value = float(value)\n                except ValueError:\n                    continue\n\n                # Special case: kBytes => bytes\n                if metric == 'Total kBytes':\n                    value = value * 1024\n\n                # Send metric as a gauge, if applicable\n                if metric in self.GAUGES:\n                    metric_count += 1\n                    metric_name = self.GAUGES[metric]\n                    self.gauge(metric_name, value, tags=tags)\n\n                # Send metric as a rate, if applicable\n                if metric in self.RATES:\n                    metric_count += 1\n                    metric_name = self.RATES[metric]\n                    self.rate(metric_name, value, tags=tags)\n\n        if metric_count == 0:\n            if self.assumed_url.get(instance['apache_status_url'], None) is None and url[-5:] != '?auto':\n                self.assumed_url[instance['apache_status_url']]= '%s?auto' % url\n                self.warning(\"Assuming url was not correct. Trying to add ?auto suffix to the url\")\n                self.check(instance)\n            else:\n                raise Exception(\"No metrics were fetched for this instance. Make sure that %s is the proper url.\" % instance['apache_status_url'])\n\n\n    @staticmethod\n    def parse_agent_config(agentConfig):\n        if not agentConfig.get('apache_status_url'):\n            return False\n\n        return {\n            'instances': [{'apache_status_url': agentConfig.get('apache_status_url')}]\n        }\n", "path": "checks.d/apache.py"}]}