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

[util] do not read hostname from datadog.conf #185

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all 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
2 changes: 0 additions & 2 deletions datadog/util/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ def is_higher_py35():

# Python 3.x
if is_p3k():
from io import StringIO
import builtins
import configparser
import urllib.request as url_lib, urllib.error, urllib.parse
Expand All @@ -51,7 +50,6 @@ def iternext(iter):
# Python 2.x
else:
import __builtin__ as builtins
from cStringIO import StringIO
from itertools import imap
import ConfigParser as configparser
import urllib2 as url_lib
Expand Down
106 changes: 1 addition & 105 deletions datadog/util/config.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,8 @@
import os
import string
import sys

# datadog
from datadog.util.compat import configparser, StringIO, is_p3k, pkg

# CONSTANTS
DATADOG_CONF = "datadog.conf"


class CfgNotFound(Exception):
pass


class PathNotFound(Exception):
pass
from datadog.util.compat import pkg


def get_os():
Expand All @@ -33,98 +21,6 @@ def get_os():
return sys.platform


def skip_leading_wsp(f):
"Works on a file, returns a file-like object"
if is_p3k():
return StringIO("\n".join(x.strip(" ") for x in f.readlines()))
else:
return StringIO("\n".join(map(string.strip, f.readlines())))


def _windows_commondata_path():
"""Return the common appdata path, using ctypes
From http://stackoverflow.com/questions/626796/\
how-do-i-find-the-windows-common-application-data-folder-using-python
"""
import ctypes
from ctypes import wintypes, windll

CSIDL_COMMON_APPDATA = 35

_SHGetFolderPath = windll.shell32.SHGetFolderPathW
_SHGetFolderPath.argtypes = [wintypes.HWND,
ctypes.c_int,
wintypes.HANDLE,
wintypes.DWORD, wintypes.LPCWSTR]

path_buf = ctypes.create_unicode_buffer(wintypes.MAX_PATH)
_SHGetFolderPath(0, CSIDL_COMMON_APPDATA, 0, 0, path_buf)
return path_buf.value


def _windows_config_path():
common_data = _windows_commondata_path()
path = os.path.join(common_data, 'Datadog', DATADOG_CONF)
if os.path.exists(path):
return path
raise PathNotFound(path)


def _unix_config_path():
path = os.path.join('/etc/dd-agent', DATADOG_CONF)
if os.path.exists(path):
return path
raise PathNotFound(path)


def _mac_config_path():
path = os.path.join('~/.datadog-agent/agent', DATADOG_CONF)
path = os.path.expanduser(path)
if os.path.exists(path):
return path
raise PathNotFound(path)


def get_config_path(cfg_path=None, os_name=None):
# Check if there's an override and if it exists
if cfg_path is not None and os.path.exists(cfg_path):
return cfg_path

if os_name is None:
os_name = get_os()

# Check for an OS-specific path, continue on not-found exceptions
if os_name == 'windows':
return _windows_config_path()
elif os_name == 'mac':
return _mac_config_path()
else:
return _unix_config_path()


def get_config(cfg_path=None, options=None):
agentConfig = {}

# Config handling
try:
# Find the right config file
path = os.path.realpath(__file__)
path = os.path.dirname(path)

config_path = get_config_path(cfg_path, os_name=get_os())
config = configparser.ConfigParser()
config.readfp(skip_leading_wsp(open(config_path)))

# bulk import
for option in config.options('Main'):
agentConfig[option] = config.get('Main', option)

except Exception:
raise CfgNotFound

return agentConfig


def get_version():
"""
Resolve `datadog` package version.
Expand Down
12 changes: 1 addition & 11 deletions datadog/util/hostname.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

# datadog
from datadog.util.compat import url_lib, is_p3k, iteritems, json
from datadog.util.config import get_config, get_os, CfgNotFound
from datadog.util.config import get_os

VALID_HOSTNAME_RFC_1123_PATTERN = re.compile(r"^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$") # noqa
MAX_HOSTNAME_LEN = 255
Expand Down Expand Up @@ -41,23 +41,13 @@ def get_hostname():

Tries, in order:

* agent config (datadog.conf, "hostname:")
* 'hostname -f' (on unix)
* socket.gethostname()
"""

hostname = None
config = None

# first, try the config
try:
config = get_config()
config_hostname = config.get('hostname')
if config_hostname and is_valid_hostname(config_hostname):
return config_hostname
except CfgNotFound:
log.info("No agent or invalid configuration file found")

# Try to get GCE instance name
if hostname is None:
gce_hostname = GCE.get_hostname(config)
Expand Down
20 changes: 0 additions & 20 deletions tests/unit/api/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,26 +66,6 @@ def test_no_initialization_fails(self):
MyCreatable.create()
self.assertEquals(self.request_mock.request.call_count, 1)

@mock.patch('datadog.util.config.get_config_path')
def test_get_hostname(self, mock_config_path):
"""
API hostname parameter fallback with Datadog Agent hostname when available.
"""
# Generate a fake agent config
tmpfilepath = os.path.join(tempfile.gettempdir(), "tmp-agentconfig")
with open(tmpfilepath, "wb") as f:
if is_p3k():
f.write(bytes("[Main]\n", 'UTF-8'))
f.write(bytes("hostname: {0}\n".format(HOST_NAME), 'UTF-8'))
else:
f.write("[Main]\n")
f.write("hostname: {0}\n".format(HOST_NAME))
# Mock get_config_path to return this fake agent config
mock_config_path.return_value = tmpfilepath

initialize()
self.assertEquals(api._host_name, HOST_NAME, api._host_name)

def test_request_parameters(self):
"""
API parameters are set with `initialize` method.
Expand Down