Debian Codegraph @

varlink/client.py

raw
1 import functools
2 import importlib.resources
3 import json
4 import os
5 import shutil
6 import signal
7 import socket
8 import subprocess
9 import sys
10 import tempfile
11 import threading
12 from typing import Optional
13
14 from .error import InterfaceNotFound, VarlinkEncoder, VarlinkError
15 from .scanner import Interface, _Method
16
17
18 class ClientInterfaceHandler:
19 """Base class for varlink client, which wraps varlink methods of an interface to the class"""
20
21 def __init__(self, interface, namespaced=False):
22 """Base class for varlink client, which wraps varlink methods of an interface.
23
24 The object allows to talk to a varlink service, which implements the specified interface
25 transparently by calling the methods. The call blocks until enough messages are received.
26
27 For monitor calls with '_more=True' a generator object is returned.
28
29 :param interface: an Interface object
30 :param namespaced: if True, varlink methods return SimpleNamespace objects instead of dictionaries
31
32 """
33 if not isinstance(interface, Interface):
34 raise TypeError
35
36 self._interface = interface
37 self._namespaced = namespaced
38 self._in_use = False
39
40 for member in interface.members.values():
41 if isinstance(member, _Method):
42 self._add_method(member)
43
44 def close(self) -> None:
45 """To be implemented."""
46 raise NotImplementedError
47
48 def _send_message(self, out) -> None:
49 """To be implemented.
50
51 This should send a varlink message to the varlink service adding a trailing zero byte.
52 """
53 raise NotImplementedError
54
55 def _next_message(self):
56 """To be implemented.
57
58 This must be a generator yielding the next received varlink message without the trailing zero byte.
59 """
60 raise NotImplementedError
61
62 def _add_method(self, method):
63 def _wrapped(*args, **kwargs):
64 if "_more" in kwargs and kwargs.pop("_more"):
65 return self._call_more(method.name, *args, **kwargs)
66 else:
67 return self._call(method.name, *args, **kwargs)
68
69 _wrapped.__name__ = method.name
70
71 # FIXME: add comments
72 if method.signature:
73 if method.doc:
74 _wrapped.__doc__ = method.doc + "\n"
75 else:
76 _wrapped.__doc__ = ""
77 "\n"
78 _wrapped.__doc__ += method.signature
79 setattr(self, method.name, _wrapped)
80
81 def _next_varlink_message(self):
82 message = next(self._next_message())
83
84 message = json.loads(message)
85 if "parameters" not in message:
86 message["parameters"] = {}
87
88 if "error" in message and message["error"] is not None:
89 self._in_use = False
90 e = VarlinkError.new(message)
91 raise e
92 else:
93 return message["parameters"], ("continues" in message) and message["continues"]
94
95 def _call(self, method_name, *args, **kwargs):
96 if self._in_use:
97 raise ConnectionError("Tried to call a varlink method, while other call still in progress")
98
99 oneway = False
100 if "_oneway" in kwargs and kwargs.pop("_oneway"):
101 oneway = True
102
103 method = self._interface.get_method(method_name)
104
105 parameters = self._interface.filter_params("client.call", method.in_type, False, args, kwargs)
106
107 out = {"method": self._interface.name + "." + method_name}
108
109 if oneway:
110 out["oneway"] = True
111
112 if parameters:
113 out["parameters"] = parameters
114
115 self._send_message(json.dumps(out, cls=VarlinkEncoder).encode("utf-8"))
116
117 if oneway:
118 return None
119
120 self._in_use = True
121 (message, more) = self._next_varlink_message()
122 if more:
123 self.close()
124 self._in_use = False
125 raise ConnectionError("Server indicated more varlink messages")
126 self._in_use = False
127
128 if message:
129 message = self._interface.filter_params(
130 "client.reply", method.out_type, self._namespaced, message, None
131 )
132
133 return message
134
135 def _call_more(self, method_name, *args, **kwargs):
136 if self._in_use:
137 raise ConnectionError("Tried to call a varlink method, while other call still in progress")
138
139 method = self._interface.get_method(method_name)
140
141 parameters = self._interface.filter_params("client.call", method.in_type, False, args, kwargs)
142 out = {"method": self._interface.name + "." + method_name, "more": True, "parameters": parameters}
143
144 self._send_message(json.dumps(out, cls=VarlinkEncoder).encode("utf-8"))
145
146 more = True
147 self._in_use = True
148 while more:
149 (message, more) = self._next_varlink_message()
150 if message:
151 message = self._interface.filter_params(
152 "client.reply", method.out_type, self._namespaced, message, None
153 )
154 yield message
155 self._in_use = False
156
157
158 class SimpleClientInterfaceHandler(ClientInterfaceHandler):
159 """A varlink client for an interface doing send/write and receive/read on a socket or file stream"""
160
161 def __init__(self, interface, file_or_socket, namespaced=False):
162 """Creates an object with the varlink methods of an interface installed.
163
164 The object allows to talk to a varlink service, which implements the specified interface
165 transparently by calling the methods. The call blocks until enough messages are received.
166
167 For monitor calls with '_more=True' a generator object is returned.
168
169 :param interface: an Interface object
170 :param file_or_socket: an open socket or io stream
171 :param namespaced: if True, varlink methods return SimpleNamespace objects instead of dictionaries
172
173 """
174 ClientInterfaceHandler.__init__(self, interface, namespaced=namespaced)
175 self._connection = file_or_socket
176
177 if hasattr(self._connection, "send_bytes"):
178 self._send_bytes = True
179 self._sendall = False
180 elif hasattr(self._connection, "sendall"):
181 self._send_bytes = False
182 self._sendall = True
183 else:
184 if not hasattr(self._connection, "write"):
185 raise TypeError
186 self._sendall = False
187 self._send_bytes = False
188
189 if hasattr(self._connection, "recv_bytes"):
190 self._recv_bytes = True
191 self._recv = False
192 elif hasattr(self._connection, "recv"):
193 self._recv = True
194 self._recv_bytes = False
195 else:
196 if not hasattr(self._connection, "read"):
197 raise TypeError
198 self._recv = False
199 self._recv_bytes = False
200
201 self._in_buffer = b""
202
203 def __enter__(self):
204 return self
205
206 def __exit__(self, _type, _value, _traceback):
207 self.close()
208
209 def close(self) -> None:
210 try:
211 if hasattr(self._connection, "shutdown"):
212 self._connection.shutdown(socket.SHUT_RDWR)
213 except Exception: # TODO: maybe just OSError?
214 pass
215
216 self._connection.close()
217
218 def _send_message(self, out) -> None:
219 if self._send_bytes:
220 self._connection.send_bytes(out + b"\0")
221 elif self._sendall:
222 self._connection.sendall(out + b"\0")
223 else:
224 self._connection.write(out + b"\0")
225
226 def _next_message(self):
227 while True:
228 message, sep, self._in_buffer = self._in_buffer.partition(b"\0")
229 if not sep:
230 # No zero byte found
231 self._in_buffer = message
232 message = None
233
234 if message:
235 yield message.decode("utf-8")
236 continue
237
238 if self._recv_bytes:
239 data = self._connection.recv_bytes(8192)
240 elif self._recv:
241 data = self._connection.recv(8192)
242 else:
243 data = self._connection.read(1)
244
245 if len(data) == 0:
246 raise BrokenPipeError("Disconnected")
247 self._in_buffer += data
248
249
250 def pipe_bridge(reader, writer):
251 recv = hasattr(reader, "recv")
252 sendall = hasattr(writer, "sendall")
253
254 while True:
255 try:
256 if recv:
257 data = reader.recv(8192)
258 else:
259 data = reader.read(1)
260 except Exception: # TODO: maybe just OsError?
261 data = []
262
263 if len(data) == 0:
264 reader.close()
265 writer.close()
266 return
267
268 try:
269 if sendall:
270 writer.sendall(data)
271 else:
272 writer.write(data)
273 writer.flush()
274 except Exception: # TODO: maybe just OsError?
275 reader.close()
276 writer.close()
277 return
278
279
280 class Client:
281 """Varlink client class.
282
283 >>> with varlink.Client("unix:/run/org.example.ping") as client, client.open('org.example.ping') as connection:
284 >>> assert connection.Ping("Test")["pong"] == "Test"
285
286 If the varlink resolver is running:
287
288 >>> client = varlink.Client(resolve_interface='com.redhat.logging')
289 >>> print(client.get_interfaces()['com.redhat.logging'].get_description())
290 # Query and monitor the log messages of a system.
291 interface com.redhat.logging
292 type Entry (cursor: string, time: string, message: string, process: string, priority: string)
293 # Monitor the log. Returns the @initial_lines most recent entries in the
294 # first reply and then continuously replies when new entries are available.
295 method Monitor(initial_lines: int) -> (entries: Entry[])
296 >>> connection = client.open("com.redhat.logging")
297
298 connection now holds an object with all the varlink methods available.
299
300 Do varlink method call with varlink arguments and a
301 single varlink return structure wrapped in a namespace class:
302
303 >>> ret = connection.Monitor(initial_lines=1)
304 >>> ret
305 namespace(entries=[namespace(cursor='s=[…]',
306 message="req:1 'dhcp4-change' [wlp3s0][…]", priority='critical',
307 process='nm-dispatcher', time='2018-01-29 12:19:59Z')])
308 >>> ret.entries[0].process
309 'nm-dispatcher'
310
311 Do varlink method call with varlink arguments and a
312 multiple return values in monitor mode, using the "_more" keyword:
313
314 >>> for m in connection.Monitor(_more=True):
315 >>> for e in m.entries:
316 >>> print(f"{e.time}: {e.message}")
317 2018-01-29 12:19:59Z: [system] Activating via systemd: service name='[…]
318 2018-01-29 12:19:59Z: Starting Network Manager Script Dispatcher Service...
319 2018-01-29 12:19:59Z: bound to 10.200.159.150 -- renewal in 1423 seconds.
320 2018-01-29 12:19:59Z: [system] Successfully activated service 'org.freedesktop.nm_dispatcher'
321 2018-01-29 12:19:59Z: Started Network Manager Script Dispatcher Service.
322 2018-01-29 12:19:59Z: req:1 'dhcp4-change' [wlp3s0]: new request (6 scripts)
323 2018-01-29 12:19:59Z: req:1 'dhcp4-change' [wlp3s0]: start running ordered scripts...
324
325 "_more" is special to this python varlink binding. If "_more=True", then the method call does
326 not return a normal namespace wrapped varlink return value, but a generator,
327 which yields the return values and waits (blocks) for the service to return more return values
328 in the generator's .__next__() call.
329 """ # noqa: E501
330
331 handler = SimpleClientInterfaceHandler
332
333 @classmethod
334 @functools.lru_cache(maxsize=1)
335 def _get_base_interface(cls):
336 return Interface(
337 importlib.resources.files("varlink").joinpath("org.varlink.service.varlink").read_text()
338 )
339
340 def __init__(self, address=None, resolve_interface=None, resolver=None):
341 """Creates a Client object to reach the interfaces of a varlink service.
342 For more constructors see the class constructor methods new_with_*() returning an Client object.
343
344 :param address: the exact address like "unix:/run/org.varlink.resolver"
345 :param resolve_interface: an interface name, which is resolved with the system wide resolver
346 :param resolver: the exact address of the resolver to be used to resolve the interface name
347 :exception ConnectionError: could not connect to the service or resolver
348
349 """
350 self._interfaces = {}
351 self._socket = None
352 self._socket_fn = None
353 self._tmpdir = None
354 self._child_pid = 0
355 self._str = "Client<uninitialized>"
356
357 self.add_interface(self._get_base_interface())
358
359 if resolve_interface:
360 self._with_interface(resolve_interface, resolver)
361
362 if address:
363 self._with_address(address)
364
365 def __enter__(self):
366 return self
367
368 def __exit__(self, exc, value, tb):
369 self.cleanup()
370
371 def __str__(self):
372 return self._str
373
374 @classmethod
375 def new_with_activate(cls, argv):
376 """Creates a Client object to a varlink service server started via socket activation.
377
378 :param argv: executable in argv[0] and parameters in argv[1:] to run the
379 varlink service server via socket activation.
380
381 """
382 return cls()._with_activate(argv)
383
384 def _with_activate(self, argv):
385 s = socket.socket(socket.AF_UNIX)
386 s.setblocking(False)
387 # TODO: this is not cleaned up
388 self._tmpdir = tempfile.mkdtemp()
389 address = f"{self._tmpdir}/{os.getpid()}"
390 s.bind(address)
391 s.listen(100)
392
393 self._child_pid = os.fork()
394 if self._child_pid == 0:
395 # child
396 n = s.fileno()
397 if n == 3:
398 # without dup() the socket is closed with the python destructor
399 n = os.dup(3)
400 del s
401 else:
402 try:
403 os.close(3)
404 except OSError:
405 pass
406
407 os.dup2(n, 3)
408 address = address.replace("\0", "@", 1)
409
410 for i in range(1, len(argv)):
411 argv[i] = argv[i].replace("$VARLINK_ADDRESS", f"unix:{address}")
412
413 os.environ["VARLINK_ADDRESS"] = f"unix:{address}"
414 os.environ["LISTEN_FDS"] = "1"
415 os.environ["LISTEN_FDNAMES"] = "varlink"
416 os.environ["LISTEN_PID"] = str(os.getpid())
417 os.execvp(argv[0], argv)
418 # TODO: this is unreachable
419 sys.exit(1)
420 # parent
421 s.close()
422
423 self._with_address("unix:" + address)
424
425 return self
426
427 @classmethod
428 def new_with_bridge(cls, argv):
429 """Creates a Client object to a varlink service started via the bridge command.
430 The bridge command like "ssh <host> varlink bridge" is executed for every connection.
431 This client object will do IO via stdio to the bridge command.
432
433 :param argv: executable in argv[0] and parameters in argv[1:] to run the
434 varlink service server via the bridge connection.
435
436 """
437 return cls()._with_bridge(argv)
438
439 def _with_bridge(self, argv):
440 def new_bridge_socket():
441 sp = socket.socketpair()
442 p = subprocess.Popen(argv, stdin=sp[1], stdout=sp[1], close_fds=True)
443 sp[1].close()
444 self._child_pid = p.pid
445 return sp[0]
446
447 def new_bridge_socket_compat() -> socket.socket:
448 sp = socket.socketpair()
449 p = subprocess.Popen(
450 " ".join(argv), shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True
451 )
452 self._child_pid = p.pid
453
454 thread1 = threading.Thread(daemon=True, target=pipe_bridge, args=(sp[1], p.stdin))
455 thread1.start()
456 thread2 = threading.Thread(daemon=True, target=pipe_bridge, args=(p.stdout, sp[1]))
457 thread2.start()
458 return sp[0]
459
460 self._str = f"Bridge with: '{' '.join(argv)}'"
461 if sys.platform == "win32":
462 self._socket_fn = new_bridge_socket_compat
463 else:
464 self._socket_fn = new_bridge_socket
465
466 return self
467
468 @classmethod
469 def new_with_address(cls, address):
470 """Creates a Client object to reach the interfaces of a varlink service.
471
472 :param address: the exact address like "unix:/run/org.varlink.resolver"
473 :exception ConnectionError: could not connect to the service or resolver
474
475 """
476
477 return cls()._with_address(address)
478
479 def _with_address(self, address):
480 if address.startswith("unix:"):
481 self._str = address
482 address = address[5:]
483 mode = address.find(";")
484 if mode != -1:
485 address = address[:mode]
486 if address[0] == "@":
487 address = address.replace("@", "\0", 1)
488
489 def open_unix():
490 s = socket.socket(socket.AF_UNIX)
491 s.setblocking(True)
492 s.connect(address)
493 return s
494
495 self._socket_fn = open_unix
496
497 elif address.startswith("tcp:"):
498 self._str = address
499 address = address[4:]
500 p = address.rfind(":")
501 if p != -1:
502 port = address[p + 1 :]
503 address = address[:p]
504 else:
505 raise ConnectionError(f"Invalid address 'tcp:{address}'")
506 address = address.replace("[", "")
507 address = address.replace("]", "")
508
509 def open_tcp():
510 s = socket.create_connection((address, int(port)))
511 s.setblocking(True)
512 return s
513
514 self._socket_fn = open_tcp
515
516 elif address is not None:
517 raise ConnectionError(f"Invalid address '{address}'")
518
519 return self
520
521 @classmethod
522 def new_with_resolved_interface(cls, interface, resolver_address=None):
523 """Creates a Client object to reach the interfaces of a varlink service.
524
525 :param interface: an interface name, which is resolved with the system wide resolver
526 :param resolver_address: the exact address of the resolver to be used to resolve the interface name
527 :exception ConnectionError: could not connect to the service or resolver
528
529 """
530
531 return cls()._with_resolved_interface(interface, resolver_address)
532
533 def _with_resolved_interface(self, interface, resolver_address=None):
534 if not resolver_address:
535 resolver_address = "unix:/run/org.varlink.resolver"
536
537 if interface == "org.varlink.resolver":
538 self._with_address(resolver_address)
539 else:
540 with (
541 Client.new_with_address(resolver_address) as client,
542 client.open("org.varlink.resolver") as _rc,
543 ):
544 # noinspection PyUnresolvedReferences
545 _r = _rc.Resolve(interface)
546 self._with_address(_r["address"])
547
548 return self
549
550 def cleanup(self) -> None:
551 if hasattr(self, "_tmpdir") and self._tmpdir is not None:
552 try:
553 shutil.rmtree(self._tmpdir)
554 except FileNotFoundError:
555 pass
556
557 if hasattr(self, "_child_pid") and self._child_pid != 0:
558 try:
559 os.kill(self._child_pid, signal.SIGTERM)
560 except OSError:
561 pass
562 try:
563 os.waitpid(self._child_pid, 0)
564 except Exception: # TODO: maybe just ChildProcessError?
565 pass
566
567 def open(
568 self, interface_name: str, namespaced: bool = False, connection: Optional[socket.socket] = None
569 ) -> SimpleClientInterfaceHandler:
570 """Open a new connection and get a client interface handle with the varlink methods installed.
571
572 :param interface_name: an interface name, which the service this client object is
573 connected to, provides.
574 :param namespaced: If arguments and return values are instances of SimpleNamespace
575 rather than dictionaries.
576 :param connection: If set, get the interface handle for an already opened connection.
577 :exception InterfaceNotFound: if the interface is not found
578
579 """
580
581 if not connection:
582 connection = self.open_connection()
583
584 if interface_name not in self._interfaces:
585 self.get_interface(interface_name, socket_connection=connection)
586
587 if interface_name not in self._interfaces:
588 raise InterfaceNotFound(interface_name)
589
590 return self.handler(self._interfaces[interface_name], connection, namespaced=namespaced)
591
592 def open_connection(self) -> socket.socket:
593 """Open a new connection and return the socket.
594 :exception OSError: anything socket.connect() throws
595
596 """
597 assert self._socket_fn, "socket_fn not initialised"
598 return self._socket_fn()
599
600 def get_interfaces(self, socket_connection=None):
601 """Returns the a list of Interface objects the service implements."""
602 if not socket_connection:
603 socket_connection = self.open_connection()
604 close_socket = True
605 else:
606 close_socket = False
607
608 # noinspection PyUnresolvedReferences
609 _service = self.handler(self._interfaces["org.varlink.service"], socket_connection)
610 self.info = _service.GetInfo()
611
612 if close_socket:
613 socket_connection.close()
614
615 return self.info["interfaces"]
616
617 def get_interface(self, interface_name, socket_connection=None):
618 if not socket_connection:
619 socket_connection = self.open_connection()
620 close_socket = True
621 else:
622 close_socket = False
623
624 _service = self.handler(self._interfaces["org.varlink.service"], socket_connection)
625 # noinspection PyUnresolvedReferences
626 desc = _service.GetInterfaceDescription(interface_name)
627 interface = Interface(desc["description"])
628 self._interfaces[interface.name] = interface
629
630 if close_socket:
631 socket_connection.close()
632
633 return interface
634
635 def add_interface(self, interface: Interface) -> None:
636 """Manually add or overwrite an interface definition from an Interface object.
637
638 :param interface: an Interface() object
639
640 """
641 if not isinstance(interface, Interface):
642 raise TypeError
643
644 self._interfaces[interface.name] = interface