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

Fix port detection when /etc/service is missing from host #1633

Merged
merged 4 commits into from
Jun 4, 2018
Merged
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
6 changes: 6 additions & 0 deletions ntp/MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
include README.md
include requirements.in
include requirements.txt
include requirements-dev.txt
graft datadog_checks
graft tests
5 changes: 5 additions & 0 deletions ntp/datadog_checks/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# (C) Datadog, Inc. 2018
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)

__path__ = __import__('pkgutil').extend_path(__path__, __name__)
3 changes: 3 additions & 0 deletions ntp/datadog_checks/ntp/__about__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@


__version__ = "1.2.0"
12 changes: 6 additions & 6 deletions ntp/datadog_checks/ntp/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from . import ntp
# (C) Datadog, Inc. 2018
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
from .ntp import NtpCheck
from .__about__ import __version__

NtpCheck = ntp.NtpCheck

__version__ = "1.2.0"

__all__ = ['ntp']
__all__ = ['NtpCheck', '__version__']
46 changes: 36 additions & 10 deletions ntp/datadog_checks/ntp/ntp.py
Original file line number Diff line number Diff line change
@@ -1,38 +1,63 @@
# (C) Datadog, Inc. 2010-2016
# (C) Datadog, Inc. 2018
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
import random
import socket

# 3p
import ntplib
from datadog_checks.checks import AgentCheck

# project
from checks import AgentCheck
from utils.ntp import NTPUtil

DEFAULT_OFFSET_THRESHOLD = 60 # in seconds
DEFAULT_HOST = '{}.datadog.pool.ntp.org'.format(random.randint(0, 3))
DEFAULT_VERSION = 3
DEFAULT_TIMEOUT = 1.0 # in seconds
DEFAULT_PORT = 'ntp'
DEFAULT_PORT_NUM = 123


class NtpCheck(AgentCheck):

DEFAULT_MIN_COLLECTION_INTERVAL = 900 # in seconds

def _get_service_port(self, instance):
"""
Get the ntp server port
"""
host = instance.get('host', DEFAULT_HOST)
port = instance.get('port', DEFAULT_PORT)
# default port is the name of the service but lookup would fail
# if the /etc/services file is missing. In that case, fallback to numeric
try:
socket.getaddrinfo(host, port)
except socket.gaierror:
port = DEFAULT_PORT_NUM

return port

def check(self, instance):
service_check_msg = None
offset_threshold = instance.get('offset_threshold', DEFAULT_OFFSET_THRESHOLD)
custom_tags = instance.get('tags', [])
try:
offset_threshold = int(offset_threshold)
except (TypeError, ValueError):
raise Exception('Must specify an integer value for offset_threshold. Configured value is %s' % repr(offset_threshold))
msg = "Must specify an integer value for offset_threshold. Configured value is {}".format(offset_threshold)
raise Exception(msg)

req_args = NTPUtil().args
req_args = {
'host': instance.get('host', DEFAULT_HOST),
'port': self._get_service_port(instance),
'version': int(instance.get('version', DEFAULT_VERSION)),
'timeout': float(instance.get('timeout', DEFAULT_TIMEOUT)),
}

self.log.debug("Using ntp host: {0}".format(req_args['host']))
self.log.debug("Using ntp host: {}".format(req_args['host']))

try:
ntp_stats = ntplib.NTPClient().request(**req_args)
except ntplib.NTPException:
self.log.debug("Could not connect to NTP Server {0}".format(
self.log.debug("Could not connect to NTP Server {}".format(
req_args['host']))
status = AgentCheck.UNKNOWN
ntp_ts = None
Expand All @@ -46,7 +71,8 @@ def check(self, instance):

if abs(ntp_offset) > offset_threshold:
status = AgentCheck.CRITICAL
service_check_msg = "Offset {0} secs higher than offset threshold ({1} secs)".format(ntp_offset, offset_threshold)
service_check_msg = "Offset {} secs higher than offset threshold ({} secs)".format(ntp_offset,
offset_threshold)
else:
status = AgentCheck.OK

Expand Down
5 changes: 1 addition & 4 deletions ntp/manifest.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
{
"maintainer": "[email protected]",
"manifest_version": "0.1.1",
"max_agent_version": "6.0.0",
"min_agent_version": "5.6.3",
"manifest_version": "1.0.0",
"name": "ntp",
"short_description": "Get alerts when your hosts drift out of sync with your chosen NTP server.",
"support": "core",
Expand All @@ -11,7 +9,6 @@
"mac_os",
"windows"
],
"version": "1.2.0",
"guid": "9d105f8c-7fd3-48d7-a5d1-1cc386ec0367",
"public_title": "Datadog-NTP Integration",
"categories":["web", "network"],
Expand Down
2 changes: 2 additions & 0 deletions ntp/requirements-dev.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
mock==2.0.0
pytest
97 changes: 20 additions & 77 deletions ntp/setup.py
Original file line number Diff line number Diff line change
@@ -1,84 +1,39 @@
# Always prefer setuptools over distutils
# (C) Datadog, Inc. 2018
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
from setuptools import setup
# To use a consistent encoding
from codecs import open
from codecs import open # To use a consistent encoding
from os import path

import json
import re
HERE = path.dirname(path.abspath(__file__))

here = path.abspath(path.dirname(__file__))

def parse_req_line(line):
line = line.strip()
if not line or line.startswith('--hash') or line[0] == '#':
return None
req = line.rpartition('#')
if len(req[1]) == 0:
line = req[2].strip()
else:
line = req[1].strip()

if '--hash=' in line:
line = line[:line.find('--hash=')].strip()
if ';' in line:
line = line[:line.find(';')].strip()
if '\\' in line:
line = line[:line.find('\\')].strip()

return line
# Get version info
ABOUT = {}
with open(path.join(HERE, 'datadog_checks', 'ntp', '__about__.py')) as f:
exec(f.read(), ABOUT)

# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
with open(path.join(HERE, 'README.md'), encoding='utf-8') as f:
long_description = f.read()

# Parse requirements
runtime_reqs = ['datadog_checks_base']
with open(path.join(here, 'requirements.txt'), encoding='utf-8') as f:
for line in f.readlines():
req = parse_req_line(line)
if req:
runtime_reqs.append(req)

def read(*parts):
with open(path.join(here, *parts), 'r') as fp:
return fp.read()

def find_version(*file_paths):
version_file = read(*file_paths)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")

# https://packaging.python.org/guides/single-sourcing-package-version/
version = find_version("datadog_checks", "ntp", "__init__.py")
# Parse requirements
def get_requirements(fpath):

manifest_version = None
with open(path.join(here, 'manifest.json'), encoding='utf-8') as f:
manifest = json.load(f)
manifest_version = manifest.get('version')
with open(path.join(HERE, fpath), encoding='utf-8') as f:
return f.readlines()

if version != manifest_version:
raise Exception("Inconsistent versioning in module and manifest - aborting wheel build")

setup(
name='datadog-ntp',
version=version,
version=ABOUT['__version__'],
description='The NTP check',
long_description=long_description,
keywords='datadog agent ntp check',

# The project's main homepage.
url='https://github.com/DataDog/integrations-core',

# Author details
author='Datadog',
author_email='[email protected]',

# License
license='MIT',
license='BSD',

# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
Expand All @@ -95,24 +50,12 @@ def find_version(*file_paths):
packages=['datadog_checks.ntp'],

# Run-time dependencies
install_requires=list(set(runtime_reqs)),

# Development dependencies, run with:
# $ pip install -e .[dev]
extras_require={
'dev': [
'check-manifest',
'datadog_agent_tk>=5.15',
],
},
install_requires=get_requirements('requirements.in')+[
'datadog_checks_base',
],

# Testing setup and dependencies
tests_require=[
'nose',
'coverage',
'datadog_agent_tk>=5.15',
],
test_suite='nose.collector',
tests_require=get_requirements('requirements-dev.txt'),

# Extra files to ship with the wheel package
package_data={b'datadog_checks.ntp': ['conf.yaml.default']},
Expand Down
65 changes: 0 additions & 65 deletions ntp/test/ci/ntp.rake

This file was deleted.

66 changes: 0 additions & 66 deletions ntp/test/test_ntp.py

This file was deleted.

File renamed without changes.
Loading