Debian Codegraph @

cylc/flow/hostuserutil.py

raw
1 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
2 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 """Host name utilities
17
18 ATTRIBUTION:
19 https://web.archive.org/web/20140606052543/http://www.linux-support.com/cms/get-local-ip-address-with-python/
20
21 Fetching the outgoing IP address of a computer might be a difficult
22 task. Computers can contain a large set of network devices, each
23 connected to different and independent sub-networks. Additionally there
24 might be available a number of devices, to be utilized in the manner of
25 network devices to exchange data with external systems.
26
27 However, if properly configured, your operating system knows what device
28 has to be utilized. Querying results depend on target addresses and
29 routing information. In our solution we are utilizing the features of
30 the local operating system to determine the correct network device. It is
31 the same step we will get the associated network address.
32
33 To reach this goal we will utilize the UDP protocol. Unlike TCP/IP, UDP
34 is a stateless networking protocol to transfer single data packages. You
35 do not have to open a point-to-point connection to a service running at
36 the target host. We have to provide the target address to enable the
37 operating system to find the correct device. Due to the nature of UDP
38 you are not required to choose a valid target address. You just have to
39 make sure your are choosing an arbitrary address from the correct
40 subnet.
41
42 The following function is temporarily opening a UDP server socket. It is
43 returning the IP address associated with this socket.
44
45 """
46
47 from contextlib import suppress
48 import os
49 import pwd
50 import socket
51 import sys
52 from time import time
53 from typing import (
54 List,
55 Optional,
56 Tuple,
57 cast,
58 )
59
60 from cylc.flow.cfgspec.glbl_cfg import glbl_cfg
61
62
63 IS_MAC_OS = 'darwin' in sys.platform.lower()
64
65
66 class HostUtil:
67 """host and user ID utility."""
68
69 EXPIRE = 3600.0 # singleton expires in 1 hour by default
70 _instance = None
71
72 @classmethod
73 def get_inst(cls, new=False, expire=None):
74 """Return the singleton instance of this class.
75
76 "new": if True, create a new singleton instance.
77 "expire":
78 the expire duration in seconds. If None or not specified, the
79 singleton expires after 3600.0 seconds (1 hour). Once expired, the
80 next call to this method will create a new singleton.
81
82 """
83 if expire is None:
84 expire = cls.EXPIRE
85 if cls._instance is None or new or time() > cls._instance.expire_time:
86 cls._instance = cls(expire)
87 return cls._instance
88
89 def __init__(self, expire):
90 self.expire_time = time() + expire
91 self._host = None # preferred name of localhost
92 self._host_exs = {} # host: socket.gethostbyname_ex(host), ...
93 self._remote_hosts = {} # host: is_remote, ...
94 self.user_pwent = None
95 self.remote_users = {}
96
97 @staticmethod
98 def get_local_ip_address(target):
99 """Return IP address of target.
100
101 This finds the external address of the particular network adapter
102 responsible for connecting to the target?
103
104 Note that although no connection is made to the target, the target
105 must be reachable on the network (or just recorded in the DNS?) or
106 the function will hang and time out after a few seconds.
107
108 """
109
110 ipaddr = ""
111 with suppress(IOError): # noqa: SIM117 (use of as convolutes this)
112 with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
113 sock.connect((target, 8000))
114 ipaddr = sock.getsockname()[0]
115 return ipaddr
116
117 @staticmethod
118 def get_host_ip_by_name(target):
119 """Return internal IP address of target."""
120 return socket.gethostbyname(target)
121
122 def _get_host_info(
123 self, target: Optional[str] = None
124 ) -> Tuple[str, List[str], List[str]]:
125 """Return the extended info of the current host."""
126 if target is None:
127 target = socket.getfqdn()
128 if IS_MAC_OS and target in {
129 f'1.{"0." * 31}ip6.arpa',
130 '1.0.0.127.in-addr.arpa',
131 }:
132 # Python's socket bindings don't play nicely with mac os
133 # so by default we get the above ip6.arpa address from
134 # socket.getfqdn, note this does *not* match `hostname -f`.
135 # https://github.com/cylc/cylc-flow/issues/2689
136 # https://github.com/cylc/cylc-flow/issues/3595
137 target = socket.gethostname()
138 if target not in self._host_exs:
139 try:
140 self._host_exs[target] = socket.gethostbyname_ex(target)
141 except IOError as exc:
142 if exc.filename is None:
143 exc.filename = target
144 raise
145 return self._host_exs[target]
146
147 @staticmethod
148 def _get_identification_cfg(key) -> str:
149 """Return the [workflow host self-identification]key global conf."""
150 return cast(
151 'str', # Possible keys: method, target, host are all strings
152 glbl_cfg().get(['scheduler', 'host self-identification', key])
153 )
154
155 def get_host(self) -> str:
156 """Return the preferred identifier for the workflow (or current) host.
157
158 As specified by the "[scheduler][host self-identification]" settings in
159 the site/user global.cylc files. This is mainly used for workflow host
160 identification by tasks.
161
162 """
163 if self._host is None:
164 hardwired = self._get_identification_cfg('host')
165 method = self._get_identification_cfg('method')
166 if method == 'address':
167 self._host = self.get_local_ip_address(
168 self._get_identification_cfg('target'))
169 elif method == 'hardwired' and hardwired:
170 self._host = hardwired
171 else: # if method == 'name':
172 self._host = self._get_host_info()[0]
173 return self._host
174
175 def get_fqdn_by_host(self, target):
176 """Return the fully qualified domain name of the target host."""
177 if not self.is_remote_host(target):
178 return self.get_host()
179 return self._get_host_info(target)[0]
180
181 def get_user(self):
182 """Return name of current user."""
183 return self._get_user_pwent().pw_name
184
185 def get_user_home(self):
186 """Return home directory of current user."""
187 return self._get_user_pwent().pw_dir
188
189 def _get_user_pwent(self):
190 """Ensure self.user_pwent is set to current user's password entry."""
191 if self.user_pwent is None:
192 my_user_name = os.environ.get('USER')
193 if my_user_name:
194 self.user_pwent = pwd.getpwnam(my_user_name)
195 else:
196 self.user_pwent = pwd.getpwuid(os.getuid())
197 self.remote_users.update(((self.user_pwent.pw_name, False),))
198 return self.user_pwent
199
200 def is_remote_host(self, name):
201 """Return True if name has different IP address than the current host.
202
203 Return False if name is None.
204 Return True if host is unknown.
205
206 """
207 if name not in self._remote_hosts:
208 if (
209 not name
210 or name.startswith("localhost") # e.g. localhost4.localdomain4
211 or name == self.get_host()
212 ):
213 self._remote_hosts[name] = False
214 else:
215 try:
216 host_info = self._get_host_info(name)
217 except IOError:
218 self._remote_hosts[name] = True
219 else:
220 self._remote_hosts[name] = (
221 host_info != self._get_host_info())
222 return self._remote_hosts[name]
223
224 def is_remote_user(self, name):
225 """Return True if name is not a name of the current user.
226
227 Return False if name is None.
228 Return True if name is not in the password database.
229 """
230 if not name:
231 return False
232 if name not in self.remote_users:
233 try:
234 self.remote_users[name] = (
235 pwd.getpwnam(name) != self._get_user_pwent())
236 except KeyError:
237 self.remote_users[name] = True
238 return self.remote_users[name]
239
240 def _is_remote_platform(self, platform):
241 """Return True if any job host in platform have different IP address
242 to the current host.
243
244 Return False if name is None.
245 Return True if host is unknown.
246
247 Todo:
248 Should this fail miserably if some hosts are remote and some are
249 not?
250 """
251 if not platform:
252 return False
253 return any(
254 is_remote_host(host)
255 for host in platform['hosts']
256 )
257
258
259 def get_host_ip_by_name(target):
260 """Shorthand for HostUtil.get_inst().get_host_ip_by_name(target)."""
261 return HostUtil.get_inst().get_host_ip_by_name(target)
262
263
264 def get_local_ip_address(target):
265 """Shorthand for HostUtil.get_inst().get_local_ip_address(target)."""
266 return HostUtil.get_inst().get_local_ip_address(target)
267
268
269 def get_host():
270 """Shorthand for HostUtil.get_inst().get_host()."""
271 return HostUtil.get_inst().get_host()
272
273
274 def get_fqdn_by_host(target):
275 """Shorthand for HostUtil.get_inst().get_fqdn_by_host(target)."""
276 return HostUtil.get_inst().get_fqdn_by_host(target)
277
278
279 def get_user():
280 """Shorthand for HostUtil.get_inst().get_user()."""
281 return HostUtil.get_inst().get_user()
282
283
284 def get_user_home():
285 """Shorthand for HostUtil.get_inst().get_user_home()."""
286 return HostUtil.get_inst().get_user_home()
287
288
289 def is_remote_platform(platform):
290 """Shorthand for HostUtil.get_inst()._is_remote_platform(host, owner)."""
291 return HostUtil.get_inst()._is_remote_platform(platform)
292
293
294 def is_remote_host(name):
295 """Shorthand for HostUtil.get_inst().is_remote_host(name)."""
296 return HostUtil.get_inst().is_remote_host(name)
297
298
299 def is_remote_user(name):
300 """Return True if name is not a name of the current user."""
301 return HostUtil.get_inst().is_remote_user(name)