Debian Codegraph @

tests/utils/udev.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 # Copyright (C) 2015 mulhern <[email protected]>
3
4 # This library is free software; you can redistribute it and/or modify it
5 # under the terms of the GNU Lesser General Public License as published by the
6 # Free Software Foundation; either version 2.1 of the License, or (at your
7 # option) any later version.
8
9 # This library is distributed in the hope that it will be useful, but WITHOUT
10 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
12 # for more details.
13
14 # You should have received a copy of the GNU Lesser General Public License
15 # along with this library; if not, write to the Free Software Foundation,
16 # Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
17 """
18 utils.udev
19 =====================
20
21 Provide access the udev device database.
22
23 Parses the udev device database from :program:`udevadm`.
24
25 .. moduleauthor:: mulhern <[email protected]>
26 """
27
28 # isort: STDLIB
29 import collections
30 import errno
31 import os
32 import re
33 import subprocess
34 import sys
35
36
37 class UDevAdm:
38 """
39 Wrap ``udevadm`` utility.
40 """
41
42 CANDIDATES = ["/sbin/udevadm", "udevadm"]
43 _adm = None
44
45 @classmethod
46 def find(cls):
47 """
48 Construct a valid :class:`UDevAdm` object.
49
50 :returns: a working :class:`UDevAdm` object
51 :rtype: :class:`UDevAdm`
52 :raises EnvironmentError:
53 """
54 for candidate in cls.CANDIDATES:
55 try:
56 udevadm = cls(candidate)
57 # try to execute udev to make sure that it's actually
58 # executable
59 udevadm.query_udev_version()
60 return udevadm
61 except EnvironmentError as error:
62 if error.errno != errno.ENOENT:
63 raise
64
65 @classmethod
66 def adm(cls):
67 """
68 Returns the singleton object of this class, if one can be found.
69
70 :returns: singleton :class:`UDevAdm` object
71 :rtype: :class:`UDevAdm`
72 """
73 if cls._adm is None:
74 try:
75 cls._adm = cls.find()
76 except EnvironmentError:
77 pass
78 return cls._adm
79
80 def __init__(self, udevadm):
81 """
82 Create a new ``udevadm`` wrapper for the given udevadm executable.
83
84 ``udevadm`` is the path to udevadm as string. If relative, ``udevadm``
85 is looked up in ``$PATH``.
86 """
87 self.udevadm = udevadm
88
89 def query_udev_version(self):
90 """
91 Return the version of udevadm.
92
93 :returns: the udevadm version
94 :rtype: int
95 """
96 return int(self._execute("--version"))
97
98 def _execute(self, *args):
99 """
100 Execute a udevadm command.
101
102 :raises CalledProcessError:
103 """
104 command = [self.udevadm] + list(args)
105 proc = subprocess.Popen(command, stdout=subprocess.PIPE)
106 output = proc.communicate()[0].strip()
107 if proc.returncode != 0:
108 raise subprocess.CalledProcessError(proc.returncode, command)
109 return output
110
111 def _execute_query(self, device_path, query_type="all"):
112 """
113 Execute a "udevadm info" query.
114
115 :raises CalledProcessError:
116 """
117 output = self._execute(
118 "info", "--root", "--path", device_path, "--query", query_type
119 )
120 return output.decode(sys.getfilesystemencoding())
121
122 def query_devices(self):
123 """
124 Generate devices from udevadm database.
125
126 Yields sys paths, minus the initial '/sys'.
127
128 :raises CalledProcessError:
129 """
130 database = (
131 self._execute("info", "--export-db")
132 .decode(sys.getfilesystemencoding())
133 .splitlines()
134 )
135
136 return (l[3:] for l in (l.strip() for l in database) if l[:3] == "P: ")
137
138 def query_device_properties(self, device_path):
139 """
140 Return map of properties.
141
142 :returns: a map of properties on the device
143 :rtype: dict of str * str
144
145 :raises CalledProcessError:
146 """
147 pairs = [
148 l.strip().split("=", 1)
149 for l in self._execute_query(device_path, "property").splitlines()
150 ]
151
152 if self.adm().query_udev_version() < 230:
153 num_pairs = len(pairs)
154 indices = [i for i in range(num_pairs) if pairs[i][1] == ""]
155 pairs = [
156 pairs[i]
157 for i in range(num_pairs)
158 if i not in indices and i - 1 not in indices
159 ]
160
161 return dict(pairs)
162
163 def query_device_attributes(self, device_path):
164 output = self._execute("info", "--attribute-walk", "--path", device_path)
165 attribute_dump = output.decode(sys.getfilesystemencoding()).splitlines()
166 attributes = {}
167 for line in attribute_dump:
168 line = line.strip()
169 if line.startswith("looking at parent device"):
170 # we don't continue with attributes of parent devices, we only
171 # want the attributes of the given device
172 break
173 if line.startswith("ATTR"):
174 name, value = line.split("==", 1)
175 # remove quotation marks from attribute value
176 value = value[1:-1]
177 # remove prefix from attribute name
178 name = re.search("{(.*)}", name).group(1)
179 attributes[name] = value
180 return attributes
181
182 def query_device(self, device_path, query_type):
183 if query_type not in ("symlink", "name"):
184 raise ValueError(query_type)
185 try:
186 return self._execute_query(device_path, query_type)
187 except subprocess.CalledProcessError:
188 return None
189
190
191 class DeviceData:
192 """
193 Data for a single device.
194 """
195
196 def __init__(self, device_path, udevadm):
197 self.device_path = device_path
198 self._udevadm = udevadm
199
200 def __repr__(self):
201 return "{0}({1})".format(self.__class__.__name__, self.device_path)
202
203 @property
204 def sys_path(self):
205 """
206 Get the ``sysfs`` path of the device.
207 """
208 return "/sys" + self.device_path
209
210 @property
211 def exists(self):
212 """
213 Whether this device has some real existance on machine.
214
215 :returns: True if the device does exist, otherwise False.
216 :rtype: bool
217 """
218 return os.path.exists(self.sys_path)
219
220 @property
221 def properties(self):
222 """
223 Get the device properties as mapping of property names as strings to
224 property values as strings.
225 """
226 return self._udevadm.query_device_properties(self.device_path)
227
228 @property
229 def attributes(self):
230 """
231 Get the device attributes as mapping of attributes names as strings to
232 property values as byte strings.
233
234 .. warning::
235
236 As ``udevadm`` only exports printable attributes, this list can be
237 incomplete! Do *not* compare this dictionary directly to a
238 attributes dictionary received through pyudev!
239 """
240 return self._udevadm.query_device_attributes(self.device_path)
241
242 @property
243 def tags(self):
244 """
245 Get the device tags as list of strings.
246 """
247 tags = self.properties.get("TAGS", "").split(":")
248 return [t for t in tags if t]
249
250 @property
251 def device_node(self):
252 """
253 Get the device node path as string, or ``None`` if the device has no
254 device node.
255 """
256 return self._udevadm.query_device(self.device_path, "name")
257
258 @property
259 def device_links(self):
260 """
261 Get the device links as list of strings.
262 """
263 links = self._udevadm.query_device(self.device_path, "symlink")
264 return links.split() if links else []
265
266 @property
267 def device_number(self):
268 """
269 Get the device number as integer or 0 if the device has no device
270 number.
271 """
272 device_node = self.device_node
273 return 0 if device_node is None else os.stat(device_node).st_rdev
274
275
276 class DeviceDatabase(collections.abc.Iterable, collections.abc.Sized):
277 """
278 The udev device database.
279
280 Takes a snapshot of the udev device database when it is initialized.
281 Consequently, some :class:`DeviceData` objects in the database may
282 not exist when the database is iterated over.
283
284 This class is an iterable over :class:`DeviceData` objects that contain the
285 data associated with each device stored in the udev database.
286 """
287
288 _db = None
289
290 @classmethod
291 def db(cls, renew=False): # pylint: disable=invalid-name
292 """
293 Get a database object.
294
295 :param bool renew: if renew is True, get a new object
296 :returns: a database object
297 :rtype: :class:`DeviceDatabase`
298 """
299 if cls._db is None or renew:
300 udevadm = UDevAdm.adm()
301 if udevadm:
302 cls._db = DeviceDatabase(udevadm)
303 return cls._db
304
305 def __init__(self, udevadm):
306 self._udevadm = udevadm
307 self._devices = set(self._udevadm.query_devices())
308
309 def __iter__(self):
310 return (
311 d for d in (DeviceData(d, self._udevadm) for d in self._devices) if d.exists
312 )
313
314 def __len__(self):
315 return sum(1 for _ in self)
316
317 def find_device_data(self, device_path):
318 """
319 Find device data for the device designated by ``device_path``.
320
321 ``device_path`` is a string containing the device path.
322
323 Return a :class:`DeviceData` object containing the data for the given
324 device, or ``None`` if the device was not found.
325 """
326 data = DeviceData(device_path, self._udevadm)
327 return data if data.exists and data in self else None