Skip to content

Commit

Permalink
Merge branch 'aliasing'
Browse files Browse the repository at this point in the history
  • Loading branch information
Matt Singleton committed Mar 6, 2013
2 parents 38a5e27 + 5318eb7 commit 84e715c
Show file tree
Hide file tree
Showing 15 changed files with 98 additions and 50 deletions.
6 changes: 3 additions & 3 deletions checks.d/elastic.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from datetime import datetime
import time

from checks import AgentCheck, gethostname
from checks import AgentCheck
from util import json, headers

HEALTH_URL = "/_cluster/health?pretty=true"
Expand Down Expand Up @@ -203,7 +203,7 @@ def process_metric(metric, xtype, path, xform=None):
if 'hostname' in node_data:
# For ES >= 0.19
hostnames = (
gethostname(self.agentConfig).decode('utf-8'),
self.hostname.decode('utf-8'),
socket.gethostname().decode('utf-8'),
socket.getfqdn().decode('utf-8')
)
Expand Down Expand Up @@ -267,7 +267,7 @@ def _metric_not_found(self, metric, path):
self.log.debug("Metric not found: %s -> %s", path, metric)

def _create_event(self, status):
hostname = gethostname(self.agentConfig).decode('utf-8')
hostname = self.hostname.decode('utf-8')
if status == "red":
alert_type = "error"
msg_title = "%s is %s" % (hostname, status)
Expand Down
2 changes: 1 addition & 1 deletion checks.d/haproxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import urllib2
import socket

from checks import AgentCheck, gethostname
from checks import AgentCheck
from util import json, headers

import time
Expand Down
14 changes: 2 additions & 12 deletions checks/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
import sys
from pprint import pprint

from util import LaconicFilter, get_os
from util import LaconicFilter, get_os, get_hostname
from config import get_confd_path
from checks import check_status

Expand Down Expand Up @@ -276,7 +276,7 @@ def __init__(self, name, init_config, agentConfig, instances=None, allow_no_data
self.name = name
self.init_config = init_config
self.agentConfig = agentConfig
self.hostname = gethostname(agentConfig)
self.hostname = get_hostname(agentConfig)
self.log = logging.getLogger('%s.%s' % (__name__, name))
self.aggregator = MetricsAggregator(self.hostname, formatter=agent_formatter)
self.events = []
Expand Down Expand Up @@ -518,16 +518,6 @@ def normalize(self, metric, prefix=None):
return name


def gethostname(agentConfig):
if agentConfig.get("hostname") is not None:
return agentConfig["hostname"]
else:
try:
return socket.getfqdn()
except socket.error, e:
log.debug("processes: unable to get hostname: " + str(e))


def agent_formatter(metric, value, timestamp, tags, hostname, device_name=None):
""" Formats metrics coming from the MetricsAggregator. Will look like:
(metric, timestamp, value, {"tags": ["tag1", "tag2"], ...})
Expand Down
4 changes: 2 additions & 2 deletions checks/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
except ImportError:
from elementtree import ElementTree

from checks import gethostname
from util import get_hostname

class Continue(Exception):
pass
Expand Down Expand Up @@ -116,7 +116,7 @@ def check(self, logger, agentConfig):
for job_dir in job_dirs:
for output in self._get_build_results(logger, job_dir):
output['api_key'] = agentConfig['api_key']
output['host'] = gethostname(agentConfig)
output['host'] = get_hostname(agentConfig)
build_events.append(output)

return build_events
Expand Down
19 changes: 8 additions & 11 deletions checks/collector.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,8 @@

import modules

from util import get_os, get_uuid, md5, Timer
from util import get_os, get_uuid, md5, Timer, get_hostname
from config import get_version
from checks import gethostname

import checks.system.unix as u
import checks.system.win32 as w32
Expand Down Expand Up @@ -107,7 +106,7 @@ def __init__(self, agentConfig, emitters, systemStats):

# Event Checks
self._event_checks = [
Nagios(socket.gethostname()),
Nagios(get_hostname()),
Hudson()
]

Expand Down Expand Up @@ -373,7 +372,7 @@ def _build_payload(self, start_event=True):
'events': {},
'metrics': [],
'resources': {},
'internalHostname' : gethostname(self.agentConfig),
'internalHostname' : get_hostname(self.agentConfig),
'uuid' : get_uuid(),
}

Expand Down Expand Up @@ -411,24 +410,22 @@ def _get_metadata(self):
metadata = self._ec2.get_metadata()
if metadata.get('hostname'):
metadata['ec2-hostname'] = metadata.get('hostname')
del metadata['hostname']

# if hostname is set in the configuration file
# use that instead of gethostname
# gethostname is vulnerable to 2 hosts: x.domain1, x.domain2
# will cause both to be aliased (see #157)
if self.agentConfig.get('hostname'):
metadata['agent-hostname'] = self.agentConfig.get('hostname')
metadata['hostname'] = metadata['agent-hostname']
else:
try:
metadata["hostname"] = socket.gethostname()
metadata["socket-hostname"] = socket.gethostname()
except:
pass
try:
metadata["fqdn"] = socket.getfqdn()
metadata["socket-fqdn"] = socket.getfqdn()
except:
pass

metadata["hostname"] = get_hostname()

return metadata

def _should_send_metadata(self):
Expand Down
3 changes: 2 additions & 1 deletion checks/db/mongo.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from datetime import datetime

from checks import *
from util import get_hostname

# When running with pymongo < 2.0
# Not the full spec for mongo URIs -- just extract username and password
Expand Down Expand Up @@ -75,7 +76,7 @@ def get_state_description(state):

return { 'timestamp': int(time.mktime(datetime.now().timetuple())),
'event_type': 'Mongo',
'host': gethostname(agentConfig),
'host': get_hostname(agentConfig),
'api_key': agentConfig['api_key'],
'version': serverVersion,
'state': get_state_description(state) }
Expand Down
6 changes: 3 additions & 3 deletions checks/nagios.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import time
import re
from util import namedtuple
from util import namedtuple, get_hostname
from utils import TailFile

# Event types we know about but decide to ignore in the parser
Expand Down Expand Up @@ -154,7 +154,7 @@ def parse_log(api_key, log_file):
import sys

logger = logging.getLogger("ddagent.checks.nagios")
nagios = Nagios(socket.gethostname())
nagios = Nagios(get_hostname())

events = nagios.check(logger, {'api_key': api_key, 'nagios_log': log_file}, move_end=False)
for e in events:
Expand All @@ -165,7 +165,7 @@ def parse_log(api_key, log_file):
import socket

logger = logging.getLogger("ddagent.checks.nagios")
nagios = Nagios(socket.gethostname())
nagios = Nagios(get_hostname())

config = {'api_key':'apikey_2','nagios_log': '/var/log/nagios3/nagios.log'}
events = nagios.check(logger, config,move_end = False)
Expand Down
5 changes: 3 additions & 2 deletions checks/system/unix.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
import subprocess
import sys
import time
from checks import Check, gethostname, UnknownValue
from checks import Check, UnknownValue
from util import get_hostname

# locale-resilient float converter
to_f = lambda s: float(s.replace(",", "."))
Expand Down Expand Up @@ -912,7 +913,7 @@ def check(self, agentConfig):

return { 'processes': processes,
'apiKey': agentConfig['api_key'],
'host': gethostname(agentConfig) }
'host': get_hostname(agentConfig) }

class Cpu(Check):
def __init__(self, logger):
Expand Down
7 changes: 3 additions & 4 deletions ddagent.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,9 @@
from tornado.options import define, parse_command_line, options

# agent import
from util import Watchdog, get_uuid
from util import Watchdog, get_uuid, get_hostname
from emitter import http_emitter, format_body
from config import get_config
from checks import gethostname
from checks.check_status import ForwarderStatus
from transaction import Transaction, TransactionManager
import modules
Expand Down Expand Up @@ -329,7 +328,7 @@ def _postMetrics(self):

if len(self._metrics) > 0:
self._metrics['uuid'] = get_uuid()
self._metrics['internalHostname'] = gethostname(self._agentConfig)
self._metrics['internalHostname'] = get_hostname(self._agentConfig)
self._metrics['apiKey'] = self._agentConfig['api_key']
MetricTransaction(self._metrics, {})
self._metrics = {}
Expand Down Expand Up @@ -390,7 +389,7 @@ def flush_trs():
if gport is not None:
log.info("Starting graphite listener on port %s" % gport)
from graphite import GraphiteServer
gs = GraphiteServer(self, gethostname(self._agentConfig), io_loop=self.mloop)
gs = GraphiteServer(self, get_hostname(self._agentConfig), io_loop=self.mloop)
if non_local_traffic is True:
gs.listen(gport)
else:
Expand Down
5 changes: 2 additions & 3 deletions dogstatsd.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,10 @@

# project
from aggregator import MetricsAggregator
from checks import gethostname
from checks.check_status import DogstatsdStatus
from config import get_config
from daemon import Daemon
from util import json, PidFile
from util import json, PidFile, get_hostname

log = logging.getLogger('dogstatsd')

Expand Down Expand Up @@ -247,7 +246,7 @@ def init(config_path=None, use_watchdog=False, use_forwarder=False):
if use_forwarder:
target = c['dogstatsd_target']

hostname = gethostname(c)
hostname = get_hostname(c)

# Create the aggregator (which is the point of communication between the
# server and reporting threads.
Expand Down
4 changes: 2 additions & 2 deletions tests/test_haproxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import os
import logging

from checks import gethostname
from util import get_hostname
from tests.common import load_check, kill_subprocess

logging.basicConfig()
Expand Down Expand Up @@ -93,7 +93,7 @@ def testCheck(self):
data = self.check._fetch_data(inst['url'], inst['username'], inst['password'])
new_data = [l.replace("OPEN", "DOWN") for l in data]

self.check._process_data(new_data, gethostname(self.agentConfig),
self.check._process_data(new_data, get_hostname(self.agentConfig),
event_cb=self.check._process_events)

assert self.check.has_events()
Expand Down
3 changes: 1 addition & 2 deletions tests/test_iis.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import logging
from nose.plugins.attrib import attr

from checks import gethostname
from tests.common import get_check

logging.basicConfig()
Expand Down Expand Up @@ -37,4 +36,4 @@ def testIIS(self):
assert tags == ['mytag1', 'mytag2']

if __name__ == "__main__":
unittest.main()
unittest.main()
3 changes: 1 addition & 2 deletions tests/test_sqlserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import logging
from nose.plugins.attrib import attr

from checks import gethostname
from tests.common import get_check

logging.basicConfig()
Expand Down Expand Up @@ -66,4 +65,4 @@ def testSqlServer(self):
assert tag.startswith('db')

if __name__ == "__main__":
unittest.main()
unittest.main()
3 changes: 1 addition & 2 deletions tests/test_win32_event_log.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import logging
from nose.plugins.attrib import attr

from checks import gethostname
from tests.common import get_check

logging.basicConfig()
Expand Down Expand Up @@ -113,4 +112,4 @@ def testIIS(self):
assert ev['tags'] == inst1['tags']

if __name__ == "__main__":
unittest.main()
unittest.main()
Loading

0 comments on commit 84e715c

Please sign in to comment.