Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[haproxy] unix socket stats urls #3005

Merged
merged 9 commits into from
Nov 17, 2016
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 49 additions & 16 deletions checks.d/haproxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,12 @@
from collections import defaultdict
import copy
import re
import socket
import time
try:
import urlparse
except LoadError:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't actually need this since the agent ships with python 2.7 (the exception name should be ImportError anyways, tests are failing on this).

simply import urlparse is ok.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(Too much Ruby on the brain.)

import urllib.parse as urlparse

# 3rd party
import requests
Expand Down Expand Up @@ -97,8 +102,20 @@ def __init__(self, name, init_config, agentConfig, instances=None):

def check(self, instance):
url = instance.get('url')
username = instance.get('username')
password = instance.get('password')
self.log.debug('Processing HAProxy data for %s' % url)

parsed_url = urlparse.urlparse(url)

if parsed_url.scheme == 'unix':
data = self._fetch_socket_data(parsed_url.path)

else:
username = instance.get('username')
password = instance.get('password')
verify = not _is_affirmative(instance.get('disable_ssl_validation', False))

data = self._fetch_url_data(url, username, password, verify)

collect_aggregates_only = _is_affirmative(
instance.get('collect_aggregates_only', True)
)
Expand Down Expand Up @@ -127,12 +144,6 @@ def check(self, instance):

custom_tags = instance.get('tags', [])

verify = not _is_affirmative(instance.get('disable_ssl_validation', False))

self.log.debug('Processing HAProxy data for %s' % url)

data = self._fetch_data(url, username, password, verify)

process_events = instance.get('status_check', self.init_config.get('status_check', False))

self._process_data(
Expand All @@ -147,19 +158,38 @@ def check(self, instance):
custom_tags=custom_tags,
)

def _fetch_data(self, url, username, password, verify):
''' Hit a given URL and return the parsed json '''
def _fetch_url_data(self, url, username, password, verify):
''' Hit a given http url and return the stats lines '''
# Try to fetch data from the stats URL

auth = (username, password)
url = "%s%s" % (url, STATS_URL)

self.log.debug("HAProxy Fetching haproxy search data from: %s" % url)
self.log.debug("Fetching haproxy stats from url: %s" % url)

response = requests.get(url, auth=auth, headers=headers(self.agentConfig), verify=verify, timeout=self.default_integration_http_timeout)
response.raise_for_status()

return response.content.splitlines()

def _fetch_socket_data(self, socket_path):
''' Hit a given stats socket and return the stats lines '''

self.log.debug("Fetching haproxy stats from socket: %s" % socket_path)

sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect(socket_path)
sock.send("show stat\r\n")

response = ""
output = sock.recv(8192)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you define this number as a constant on the top of the module? Like:
BUFSIZE=8192

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

while output:
response += output.decode("ASCII")
output = sock.recv(8192)

r = requests.get(url, auth=auth, headers=headers(self.agentConfig), verify=verify, timeout=self.default_integration_http_timeout)
r.raise_for_status()
sock.close()
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.


return r.content.splitlines()
return response.splitlines()

def _process_data(self, data, collect_aggregates_only, process_events, url=None,
collect_status_metrics=False, collect_status_metrics_by_host=False,
Expand Down Expand Up @@ -428,8 +458,11 @@ def _process_metrics(self, data, url, services_incl_filter=None,
hostname = data['svname']
service_name = data['pxname']
back_or_front = data['back_or_front']
tags = ["type:%s" % back_or_front, "instance_url:%s" % url]
tags.append("service:%s" % service_name)
tags = [
"type:%s" % back_or_front,
"instance_url:%s" % url,
"service:%s" % service_name,
]
tags.extend(custom_tags)

if self._is_service_excl_filtered(service_name, services_incl_filter,
Expand Down
7 changes: 6 additions & 1 deletion ci/haproxy.rb
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,13 @@ def haproxy_rootdir

task before_script: ['ci:common:before_script'] do
%w(haproxy haproxy-open).each do |name|
# Older haproxy doesn't support ENV interpolation
config = File.read("#{ENV['TRAVIS_BUILD_DIR']}/ci/resources/haproxy/#{name}.cfg")
config.gsub!('$VOLATILE_DIR', ENV['VOLATILE_DIR'])
File.write("#{ENV['VOLATILE_DIR']}/#{name}.cfg", config)

pid = spawn("#{haproxy_rootdir}/haproxy", '-d', '-f',
"#{ENV['TRAVIS_BUILD_DIR']}/ci/resources/haproxy/#{name}.cfg",
"#{ENV['VOLATILE_DIR']}/#{name}.cfg",
out: '/dev/null')
Process.detach(pid)
sh %(echo #{pid} > $VOLATILE_DIR/#{name}.pid)
Expand Down
1 change: 1 addition & 0 deletions ci/resources/haproxy/haproxy.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
global
log 127.0.0.1 local0
maxconn 4096
stats socket $VOLATILE_DIR/datadog-haproxy-stats.sock

defaults
log global
Expand Down
4 changes: 4 additions & 0 deletions conf.d/haproxy.yaml.example
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ instances:
# username: username
# password: password
#
# or, with a unix stats or admin socket:
#
# url: unix:///var/run/haproxy.sock
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nitpick: could you add a leading - to the example so it's clear that should be another instance and not an attribute of the first one?

 instances:
   - url: http://localhost/admin?stats
      # username: username
      # password: password
   # or, with a unix stats or admin socket:
   # - url: unix:///var/run/haproxy.sock

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, that looks odd to me, but updated.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah at first I thought it'd be clearer but doesn't seem so...
Feel free to adjust it as you think it's better from the user perspective, or leave it as it is and we'll fix that later.

#
# The (optional) `status_check` paramater will instruct the check to
# send events on status changes in the backend. This is DEPRECATED in
# favor creation a monitor on the service check status and will be
Expand Down
19 changes: 19 additions & 0 deletions tests/checks/integration/test_haproxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,14 @@ def __init__(self, *args, **kwargs):
'collect_aggregates_only': False,
}]
}
self.unixsocket_path = os.path.join(os.environ['VOLATILE_DIR'], 'datadog-haproxy-stats.sock')
self.unixsocket_url = 'unix://{0}'.format(self.unixsocket_path)
self.config_unixsocket = {
'instances': [{
'url': self.unixsocket_url,
'collect_aggregates_only': False,
}]
}

def _test_frontend_metrics(self, shared_tag):
frontend_tags = shared_tag + ['type:FRONTEND', 'service:public']
Expand Down Expand Up @@ -205,3 +213,14 @@ def test_open_config(self):
self.assertEquals(self.service_checks[0]['host_name'], '')

self.coverage_report()

def test_unixsocket_config(self):
self.run_check_twice(self.config_unixsocket)

shared_tag = ['instance_url:{0}'.format(self.unixsocket_url)]

self._test_frontend_metrics(shared_tag)
self._test_backend_metrics(shared_tag)
self._test_service_checks()

self.coverage_report()