Esempio n. 1
0
    def _verify_ipaddress(self):
        if not self._ipaddress:
            raise MKIPAddressLookupError("Host as no IP address configured.")

        if self._ipaddress in ["0.0.0.0", "::"]:
            raise MKIPAddressLookupError(
                "Failed to lookup IP address and no explicit IP address configured")
Esempio n. 2
0
def cached_dns_lookup(hostname, family):
    # type: (str, int) -> Optional[str]
    cache = cmk_base.config_cache.get_dict("cached_dns_lookup")
    cache_id = hostname, family

    # Address has already been resolved in prior call to this function?
    try:
        return cache[cache_id]
    except KeyError:
        pass

    # Prepare file based fall-back DNS cache in case resolution fails
    # TODO: Find a place where this only called once!
    ip_lookup_cache = _initialize_ip_lookup_cache()

    cached_ip = ip_lookup_cache.get(cache_id)
    if cached_ip and config.use_dns_cache:
        cache[cache_id] = cached_ip
        return cached_ip

    host_config = config.get_config_cache().get_host_config(hostname)

    if host_config.is_no_ip_host:
        cache[cache_id] = None
        return None

    # Now do the actual DNS lookup
    try:
        ipa = socket.getaddrinfo(
            hostname, None, family == 4 and socket.AF_INET
            or socket.AF_INET6)[0][4][0]

        # Update our cached address if that has changed or was missing
        if ipa != cached_ip:
            console.verbose("Updating IPv%d DNS cache for %s: %s\n" %
                            (family, hostname, ipa))
            _update_ip_lookup_cache(cache_id, ipa)

        cache[cache_id] = ipa  # Update in-memory-cache
        return ipa

    except (MKTerminate, MKTimeout):
        # We should be more specific with the exception handler below, then we
        # could drop this special handling here
        raise

    except Exception as e:
        # DNS failed. Use cached IP address if present, even if caching
        # is disabled.
        if cached_ip:
            cache[cache_id] = cached_ip
            return cached_ip
        else:
            cache[cache_id] = None
            raise MKIPAddressLookupError(
                "Failed to lookup IPv%d address of %s via DNS: %s" %
                (family, hostname, e))