net.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #
  2. # Licensed to the Apache Software Foundation (ASF) under one
  3. # or more contributor license agreements. See the NOTICE file
  4. # distributed with this work for additional information
  5. # regarding copyright ownership. The ASF licenses this file
  6. # to you under the Apache License, Version 2.0 (the
  7. # "License"); you may not use this file except in compliance
  8. # with the License. You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing,
  13. # software distributed under the License is distributed on an
  14. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. # KIND, either express or implied. See the License for the
  16. # specific language governing permissions and limitations
  17. # under the License.
  18. from __future__ import annotations
  19. import socket
  20. from functools import lru_cache
  21. from airflow.configuration import conf
  22. # patched version of socket.getfqdn() - see https://github.com/python/cpython/issues/49254
  23. @lru_cache(maxsize=None)
  24. def getfqdn(name=""):
  25. """
  26. Get fully qualified domain name from name.
  27. An empty argument is interpreted as meaning the local host.
  28. """
  29. name = name.strip()
  30. if not name or name == "0.0.0.0":
  31. name = socket.gethostname()
  32. try:
  33. addrs = socket.getaddrinfo(name, None, 0, socket.SOCK_DGRAM, 0, socket.AI_CANONNAME)
  34. except OSError:
  35. pass
  36. else:
  37. for addr in addrs:
  38. if addr[3]:
  39. name = addr[3]
  40. break
  41. return name
  42. def get_host_ip_address():
  43. """Fetch host ip address."""
  44. return socket.gethostbyname(getfqdn())
  45. def get_hostname():
  46. """Fetch the hostname using the callable from config or use `airflow.utils.net.getfqdn` as a fallback."""
  47. return conf.getimport("core", "hostname_callable", fallback="airflow.utils.net.getfqdn")()