コード例 #1
0
    def __init__(self, config):
        parser = argparse.ArgumentParser()
        parser.add_argument('--from-cron', action='store_true')
        parser.add_argument('--debug', action='store_true')
        args = parser.parse_args()

        log_level = logging.INFO
        if args.from_cron:
            log_level = logging.WARN
        elif args.debug:
            log_level = logging.DEBUG

        log_format = config.get_log_format(self.__class__.__name__)
        logging.basicConfig(
            filename=config.get_logging_config().get('collector_log_file'),
            format=log_format,
            level=log_level,
        )

        if not args.from_cron:
            console = logging.StreamHandler()
            console.setLevel(log_level)
            console.setFormatter(logging.Formatter(log_format))
            logging.getLogger('').addHandler(console)

        try:
            agent_config = get_config()
            if 'api_key' in agent_config:
                api_key = agent_config['api_key']
        except:
            api_key = os.environ['DD_API_KEY']

        initialize(api_key=api_key)
コード例 #2
0
def get_hostname(hostname_from_config):
    # type: (bool) -> Optional[str]
    """
    Get the canonical host name this agent should identify as. This is
    the authoritative source of the host name for the agent.

    Tries, in order:

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

    hostname = None
    config = None

    # first, try the config if hostname_from_config is set to True
    try:
        if hostname_from_config:
            config = get_config()
            config_hostname = config.get('hostname')
            if config_hostname and is_valid_hostname(config_hostname):
                log.warning(
                    "Hostname lookup from agent configuration will be deprecated "
                    "in an upcoming version of datadogpy. Set hostname_from_config to False "
                    "to get rid of this warning")
                return config_hostname
    except CfgNotFound:
        log.warning("No agent or invalid configuration file found")

    # Try to get GCE instance name
    if hostname is None:
        gce_hostname = GCE.get_hostname(config)
        if gce_hostname is not None:
            if is_valid_hostname(gce_hostname):
                return gce_hostname
    # then move on to os-specific detection
    if hostname is None:

        def _get_hostname_unix():
            try:
                # try fqdn
                p = subprocess.Popen(['/bin/hostname', '-f'],
                                     stdout=subprocess.PIPE,
                                     stderr=subprocess.DEVNULL)
                out, err = p.communicate()
                if p.returncode == 0:
                    if is_p3k():
                        return out.decode("utf-8").strip()
                    else:
                        return out.strip()
            except Exception:
                return None

        os_name = get_os()
        if os_name in ['mac', 'freebsd', 'linux', 'solaris']:
            unix_hostname = _get_hostname_unix()
            if unix_hostname and is_valid_hostname(unix_hostname):
                hostname = unix_hostname

    # if we have an ec2 default hostname, see if there's an instance-id available
    if hostname is not None and True in [
            hostname.lower().startswith(p) for p in [u'ip-', u'domu']
    ]:
        instanceid = EC2.get_instance_id(config)
        if instanceid:
            hostname = instanceid

    # fall back on socket.gethostname(), socket.getfqdn() is too unreliable
    if hostname is None:
        try:
            socket_hostname = socket.gethostname()  # type: Optional[str]
        except socket.error:
            socket_hostname = None
        if socket_hostname and is_valid_hostname(socket_hostname):
            hostname = socket_hostname

    if hostname is None:
        log.warning(
            u"Unable to reliably determine host name. You can define one in your `hosts` file, "
            u"or in `datadog.conf` file if you have Datadog Agent installed.")

    return hostname
コード例 #3
0
def get_hostname():
    """
    Get the canonical host name this agent should identify as. This is
    the authoritative source of the host name for the agent.

    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)
        if gce_hostname is not None:
            if is_valid_hostname(gce_hostname):
                return gce_hostname
    # then move on to os-specific detection
    if hostname is None:

        def _get_hostname_unix():
            try:
                # try fqdn
                p = subprocess.Popen(['/bin/hostname', '-f'],
                                     stdout=subprocess.PIPE)
                out, err = p.communicate()
                if p.returncode == 0:
                    if is_p3k():
                        return out.decode("utf-8").strip()
                    else:
                        return out.strip()
            except Exception:
                return None

        os_name = get_os()
        if os_name in ['mac', 'freebsd', 'linux', 'solaris']:
            unix_hostname = _get_hostname_unix()
            if unix_hostname and is_valid_hostname(unix_hostname):
                hostname = unix_hostname

    # if we have an ec2 default hostname, see if there's an instance-id available
    if hostname is not None and True in [
            hostname.lower().startswith(p) for p in [u'ip-', u'domu']
    ]:
        instanceid = EC2.get_instance_id(config)
        if instanceid:
            hostname = instanceid

    # fall back on socket.gethostname(), socket.getfqdn() is too unreliable
    if hostname is None:
        try:
            socket_hostname = socket.gethostname()
        except socket.error:
            socket_hostname = None
        if socket_hostname and is_valid_hostname(socket_hostname):
            hostname = socket_hostname

    if hostname is None:
        log.critical(
            "Unable to reliably determine host name. You can define one"
            " in datadog.conf or in your hosts file")
        raise Exception(
            "Unable to reliably determine host name. You can define"
            " one in datadog.conf or in your hosts file")
    else:
        return hostname
コード例 #4
0
ファイル: hostname.py プロジェクト: bitshark/datadogpy
def get_hostname():
    """
    Get the canonical host name this agent should identify as. This is
    the authoritative source of the host name for the agent.

    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)
        if gce_hostname is not None:
            if is_valid_hostname(gce_hostname):
                return gce_hostname
    # then move on to os-specific detection
    if hostname is None:
        def _get_hostname_unix():
            try:
                # try fqdn
                p = subprocess.Popen(['/bin/hostname', '-f'], stdout=subprocess.PIPE)
                out, err = p.communicate()
                if p.returncode == 0:
                    if is_p3k():
                        return out.decode("utf-8").strip()
                    else:
                        return out.strip()
            except Exception:
                return None

        os_name = get_os()
        if os_name in ['mac', 'freebsd', 'linux', 'solaris']:
            unix_hostname = _get_hostname_unix()
            if unix_hostname and is_valid_hostname(unix_hostname):
                hostname = unix_hostname

    # if we have an ec2 default hostname, see if there's an instance-id available
    if hostname is not None and True in [hostname.lower().startswith(p) for p in [u'ip-', u'domu']]:
        instanceid = EC2.get_instance_id(config)
        if instanceid:
            hostname = instanceid

    # fall back on socket.gethostname(), socket.getfqdn() is too unreliable
    if hostname is None:
        try:
            socket_hostname = socket.gethostname()
        except socket.error:
            socket_hostname = None
        if socket_hostname and is_valid_hostname(socket_hostname):
            hostname = socket_hostname

    if hostname is None:
        log.critical("Unable to reliably determine host name. You can define one"
                     " in datadog.conf or in your hosts file")
        raise Exception("Unable to reliably determine host name. You can define"
                        " one in datadog.conf or in your hosts file")
    else:
        return hostname