VARLINK(1)
π NAME π
okay so, bestie, listen up: varlink β this is the varlink Documentation. π
It's an implementation of the varlink protocol. no cap. β¨
See <https://www.varlink.org> for more information about the varlink protocol and interface definition files. π
- π₯οΈ For server implementations use the
varlink.Serverclass. - π For client implementations use the
varlink.Clientclass. - π¦ For installation and examples, see the GIT repository <https://github.com/varlink/python>. or the source code <_modules/varlink/tests/test_orgexamplemore.html> of
varlink.tests.test_orgexamplemore
π class varlink.Client π
class varlink.Client(address=None, resolve_interface=None, resolver=None)
Bases: object
Varlink client class. it's giving main character energy fr fr. π«Ά
>>> with varlink.Client("unix:/run/org.example.ping") as client, client.open('org.example.ping') as connection:
>>> assert connection.Ping("Test")["pong"] == "Test"
If the varlink resolver is running:
>>> client = varlink.Client(resolve_interface='com.redhat.logging')
>>> print(client.get_interfaces()['com.redhat.logging'].get_description())
# Query and monitor the log messages of a system.
interface com.redhat.logging
type Entry (cursor: string, time: string, message: string, process: string, priority: string)
# Monitor the log. Returns the @initial_lines most recent entries in the
# first reply and then continuously replies when new entries are available.
method Monitor(initial_lines: int) -> (entries: Entry[])
>>> connection = client.open("com.redhat.logging")
connection now holds an object with all the varlink methods available. literally everything, it ate. π
Do varlink method call with varlink arguments and a single varlink return structure wrapped in a namespace class:
>>> ret = connection.Monitor(initial_lines=1)
>>> ret
namespace(entries=[namespace(cursor='s=[β¦]',
message="req:1 'dhcp4-change' [wlp3s0][β¦]", priority='critical',
process='nm-dispatcher', time='2018-01-29 12:19:59Z')])
>>> ret.entries[0].process
'nm-dispatcher'
Do varlink method call with varlink arguments and a multiple return values in monitor mode, using the "_more" keyword:
>>> for m in connection.Monitor(_more=True):
>>> for e in m.entries:
>>> print(f"{e.time}: {e.message}")
2018-01-29 12:19:59Z: [system] Activating via systemd: service name='[β¦]
2018-01-29 12:19:59Z: Starting Network Manager Script Dispatcher Service...
2018-01-29 12:19:59Z: bound to 10.200.159.150 -- renewal in 1423 seconds.
2018-01-29 12:19:59Z: [system] Successfully activated service 'org.freedesktop.nm_dispatcher'
2018-01-29 12:19:59Z: Started Network Manager Script Dispatcher Service.
2018-01-29 12:19:59Z: req:1 'dhcp4-change' [wlp3s0]: new request (6 scripts)
2018-01-29 12:19:59Z: req:1 'dhcp4-change' [wlp3s0]: start running ordered scripts...
"_more" is special to this python varlink binding. π§ If "_more=True", then the method call does not return a normal namespace wrapped varlink return value, but a generator, which yields the return values and waits (blocks) for the service to return more return values in the generator's .__next__() call. the way that it just sits there and waits... iconic honestly. π
π Client methods π
__init__(address=None, resolve_interface=None, resolver=None)β Creates a Client object to reach the interfaces of a varlink service. For more constructors see the class constructor methodsnew_with_*()returning an Client object. π- Parameters
- address β the exact address like
"unix:/run/org.varlink.resolver" - resolve_interface β an interface name, which is resolved with the system wide resolver
- resolver β the exact address of the resolver to be used to resolve the interface name
- address β the exact address like
- Raises
ConnectionErrorβ could not connect to the service or resolver π
- Parameters
add_interface(interface: Interface) -> Noneβ Manually add or overwrite an interface definition from an Interface object.- Parameters
- interface β an
Interface()object
- interface β an
- Parameters
cleanup() -> Noneβ that's it, that's the whole thing. πget_interface(interface_name, socket_connection=None)get_interfaces(socket_connection=None)β Returns the a list of Interface objects the service implements. yes, "the a list", we don't edit the source copy bestie, we just vibe with it. πhandlerβ alias ofSimpleClientInterfaceHandlerclassmethod new_with_activate(argv)β Creates a Client object to a varlink service server started via socket activation. π₯- Parameters
- argv β executable in
argv[0]and parameters inargv[1:]to run the varlink service server via socket activation.
- argv β executable in
- Parameters
classmethod new_with_address(address)β Creates a Client object to reach the interfaces of a varlink service. π¦- Parameters
- address β the exact address like
"unix:/run/org.varlink.resolver"
- address β the exact address like
- Raises
ConnectionErrorβ could not connect to the service or resolver π
- Parameters
classmethod new_with_bridge(argv)β Creates a Client object to a varlink service started via the bridge command. The bridge command like"ssh <host> varlink bridge"is executed for every connection. This client object will do IO viastdioto the bridge command. π°οΈ- Parameters
- argv β executable in
argv[0]and parameters inargv[1:]to run the varlink service server via the bridge connection.
- argv β executable in
- Parameters
classmethod new_with_resolved_interface(interface, resolver_address=None)β Creates a Client object to reach the interfaces of a varlink service. β¨- Parameters
- interface β an interface name, which is resolved with the system wide resolver
- resolver_address β the exact address of the resolver to be used to resolve the interface name
- Raises
ConnectionErrorβ could not connect to the service or resolver π
- Parameters
open(interface_name: str, namespaced: bool = False, connection: socket | None = None) -> SimpleClientInterfaceHandlerβ Open a new connection and get a client interface handle with the varlink methods installed. periodt. π- Parameters
- interface_name β an interface name, which the service this client object is connected to, provides.
- namespaced β If arguments and return values are instances of
SimpleNamespacerather than dictionaries. - connection β If set, get the interface handle for an already opened connection.
- Raises
InterfaceNotFoundβ if the interface is not found π
- Parameters
open_connection() -> socketβ Open a new connection and return the socket.:exception OSError: anything socket.connect() throwsπ
π class varlink.ClientInterfaceHandler π
class varlink.ClientInterfaceHandler(interface, namespaced=False)
Bases: object
Base class for varlink client, which wraps varlink methods of an interface to the class. πΈ
__init__(interface, namespaced=False)β Base class for varlink client, which wraps varlink methods of an interface.
The object allows to talk to a varlink service, which implements the specified interface transparently by calling the methods. The call blocks until enough messages are received. π΄
For monitor calls with '_more=True' a generator object is returned.
Parameters
- interface β an
Interfaceobject - namespaced β if
True, varlink methods returnSimpleNamespaceobjects instead of dictionaries
close() -> Noneβ To be implemented. (someday bestie, someday π )
β class varlink.ForkingServer β
class varlink.ForkingServer(server_address, RequestHandlerClass, bind_and_activate=True)
Bases: ForkingMixIn, Server
πΈ class varlink.Interface πΈ
class varlink.Interface(description)
Bases: object
Class for a parsed varlink interface definition. π§
__init__(description)β description β description string in varlink interface definition languagefilter_params(parent_name, varlink_type, _namespaced, args, kwargs)get_description()β return the description string in varlink interface definition languageget_method(name)
π exception varlink.InterfaceNotFound π
exception varlink.InterfaceNotFound(interface)
Bases: VarlinkError
The standardized varlink InterfaceNotFound error as a python exception. π
__init__(interface)classmethod new(message, namespaced=False)
π exception varlink.InvalidParameter π
exception varlink.InvalidParameter(name)
Bases: VarlinkError
The standardized varlink InvalidParameter error as a python exception. π
__init__(name)classmethod new(message, namespaced=False)
π exception varlink.MethodNotFound π
exception varlink.MethodNotFound(method)
Bases: VarlinkError
The standardized varlink MethodNotFound error as a python exception. π
__init__(method)classmethod new(message, namespaced=False)
π exception varlink.MethodNotImplemented π
exception varlink.MethodNotImplemented(method)
Bases: VarlinkError
The standardized varlink MethodNotImplemented error as a python exception. π
__init__(method)classmethod new(message, namespaced=False)
π«Ά class varlink.RequestHandler π«Ά
class varlink.RequestHandler(request, client_address, server)
Bases: StreamRequestHandler
Varlink request handler. π§
To use as an argument for the VarlinkServer constructor. Instantiate your own class and set the class variable service to your global Service object.
handle()service: Service | None = None
π¦ class varlink.Scanner π¦
class varlink.Scanner(string)
Bases: object
Class for scanning a varlink interface definition. π
__init__(string)end()
okay so the method tour keeps going β here's the tail end of that class, and ngl the original ships these with zero description, so I'm handing you the exact signatures and nothing more, iykyk:
expect(expected)β¨get(expected)β¨read_member()πread_struct()πread_type(lastmaybe=False)πΈ βlastmaybedefaults toFalseand that is genuinely all the tea we get.
π«Ά class varlink.Server π«Ά
Bases: BaseServer
It's giving literally the same as the standard socketserver.TCPServer, except you initialize it with a subclass of RequestHandler. That's the whole plot, no notes. π₯
>>> import varlink
>>> import os
>>> import sys
>>>
>>> service = varlink.Service(vendor='Example', product='Examples', version='1', url='http://example.com',
>>> interface_dir=os.path.dirname(__file__))
>>>
>>> class ServiceRequestHandler(varlink.RequestHandler):
>>> service = service
>>>
>>> @service.interface('com.example.service')
>>> class Example:
>>> # com.example.service method implementation here β¦
>>> pass
>>>
>>> server = varlink.ThreadingServer(sys.argv[1][10:], ServiceRequestHandler)
>>> server.serve_forever()
And now the members, bestie:
__init__(server_address, RequestHandlerClass, bind_and_activate=True)β the constructor. You may extend it, but do not override it, okay? πaddress_family = 2β just a class attribute, chilling, being2. πallow_reuse_address = Trueclose_request(request)β called to clean up an individual request. π§Ήfileno() -> intβ returns the socket file number. Interface required by selector.get_request()β grabs the request and the client address from the socket. May be overridden. πrequest_queue_size = 5server_activate()β called by the constructor to activate the server. May be overridden.server_bind()β called by the constructor to bind the socket. May be overridden.server_close()β called to clean-up the server. May be overridden.shutdown_request(request)β called to shutdown and close an individual request. πsocket_type = 1
π class varlink.Service π
varlink.Service(vendor='', product='', version='', url='', interface_dir='.', namespaced=False, *, json_encoder_cls=None)
Bases: object
The varlink service server handler. π
To use the Service, a global object gets instantiated, like this:
>>> service = Service(
>>> vendor='Red Hat',
>>> product='Manage System Accounts',
>>> version='1',
>>> interface_dir=os.path.dirname(__file__)
>>> )
And for the class implementing the methods of a specific varlink interface, you use a decorator:
>>> @service.interface('com.redhat.system.accounts')
>>> class Accounts:
>>> pass
The varlink file that corresponds to this interface is loaded from the 'interface_dir' you specified in the constructor of the Service. It has to end in '.varlink' β periodt. β¨
Use a RequestHandler with your Service object, and run a Server with it.
If you want to use your own server with the Service object, split the incoming stream for every null byte and feed it to the Service.handle() method. Write any message returned from this generator function to the output stream. π¦
>>> for outgoing_message in service.handle(incoming_message):
>>> connection.write(outgoing_message)
π Note: varlink only handles one method call at a time on one connection. One. Call. At. A. Time.
Now the methods:
GetInfo()β the standardizedorg.varlink.service.GetInfo()varlink method. πGetInterfaceDescription(interface: str) -> dict[str, str]β the standardizedorg.varlink.service.GetInterfaceDescription()varlink method. π__init__(vendor='', product='', version='', url='', interface_dir='.', namespaced=False, *, json_encoder_cls=None)β initializes the service with the data thatorg.varlink.service.GetInfo()returns.- Parameters
interface_dirβ the directory with the*.varlinkfiles for the interfaces πjson_encoder_clsβ Optional; supply ajson.JSONEncodersubclass to use instead of the default
- Parameters
handle(message, _server=None, _request=None)β this generator function handles any incoming message. Write any returned bytes to the output stream.
>>> for outgoing_message in service.handle(incoming_message):
>>> connection.write(outgoing_message)
interface(filename)β and that's the whole thing, no extra notes. π
πΈ class varlink.SimpleClientInterfaceHandler(interface, file_or_socket, namespaced=False) πΈ
Bases: ClientInterfaceHandler
A varlink client for an interface doing send/write and receive/read on a socket or file stream. π«Ά
__init__(interface, file_or_socket, namespaced=False) β creates an object with the varlink methods of an interface installed.
The object lets you talk to a varlink service that implements the specified interface, transparently, just by calling the methods. The call blocks until enough messages are received. π
For monitor calls with '_more=True' a generator object is returned.
- Parameters
interfaceβ anInterfaceobjectfile_or_socketβ an open socket or io streamnamespacedβ ifTrue, varlink methods returnSimpleNamespaceobjects instead of dictionaries
close() -> None β To be implemented. Yep, that's the entire note. π
π§ class varlink.ThreadingServer(server_address, RequestHandlerClass, bind_and_activate=True) π§
Bases: ThreadingMixIn, Server
That's genuinely the whole entry β no extra prose, the mixins do the talking. β¨
β class varlink.VarlinkEncoder β
varlink.VarlinkEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)
Bases: JSONEncoder
The Encoder used to encode JSON. π
default(o) β implement this method in a subclass so it returns a serializable object for o, or calls the base implementation (which raises a TypeError).
For example, to support arbitrary iterators, you could implement default like this:
def default(self, o):
try:
iterable = iter(o)
except TypeError:
pass
else:
return list(iterable)
# Let the base class default method raise the TypeError
return super().default(o)
π exception varlink.VarlinkError(message, namespaced=False) π
Bases: Exception
The base class for varlink error exceptions. π
__init__(message, namespaced=False)as_dict()error()β returns the exception varlink error nameclassmethod new(message, namespaced=False)parameters(namespaced=False)β returns the exception varlink error parameters
varlink.get_listen_fd() -> int | None β that's the entire signature, sitting right there at module level. π
π₯ EXAMPLE π₯
Server and Client example of varlink for python. ππ
From the main git repository directory run:
$ PYTHONPATH=$(pwd) python3 ./varlink/tests/test_orgexamplemore.py
or:
$ PYTHONPATH=$(pwd) python3 ./varlink/tests/test_orgexamplemore.py --varlink="unix:@test" &
Listening on @test
[1] 6434
$ PYTHONPATH=$(pwd) python3 ./varlink/tests/test_orgexamplemore.py --client --varlink="unix:@test"
[...]
And the little test-module crew that shows up in all of this:
- exception
varlink.tests.test_orgexamplemore.ActionFailed(reason)π - class
varlink.tests.test_orgexamplemore.ServiceRequestHandler(request, client_address, server) - class
varlink.tests.test_orgexamplemore.TestService(methodName='runTest')
π§ͺ TESTING π§ͺ
varlink.mock.mockedservice(fake_service=None, fake_types=None,
address='unix:@test', name=None, vendor='varlink', product='mock',
version=1, url='http://localhost')
okay bestie, this one is the Varlink mocking service π It exists so you can mock a fake service and, like, merely test your varlink client against it. That's the whole assignment.
The mocking feature is for testing purpose β it lets you test your varlink client against a fake service which will return the self-handed result you defined in the object you're mocking. No cap, it's literally that.
Example:
>>> import unittest
>>> from varlink import mock
>>> import varlink
>>>
>>>
>>> types = '''
>>> type MyPersonalType (
>>> foo: string,
>>> bar: string,
>>> )
>>> '''
>>>
>>>
>>> class Service():
>>>
>>> def Test1(self, param1: int) -> dict:
>>> '''
>>> return test: MyPersonalType
>>> '''
>>> return {
>>> "test": {
>>> "foo": "bim",
>>> "bar": "boom"
>>> }
>>> }
>>>
>>> def Test2(self, param1: str) -> dict:
>>> '''
>>> return (test: string)
>>> '''
>>> return {"test": param1}
>>>
>>> def Test3(self, param1: int) -> dict:
>>> '''
>>> return (test: int, boom: string, foo: string, bar: 42)
>>> '''
>>> return {
>>> "test": param1 * 2,
>>> "boom": "foo",
>>> "foo": "bar",
>>> "bar": 42,
>>> }
>>>
>>>
>>> class TestMyClientWithMockedService(unittest.TestCase):
>>>
>>> @mock.mockedservice(
>>> fake_service=Service,
>>> fake_types=types,
>>> name='org.service.com',
>>> address='unix:@foo'
>>> )
>>> def test_my_client_against_a_mock(self):
>>> with varlink.Client("unix:@foo") as client:
>>> connection = client.open('org.service.com')
>>> self.assertEqual(
>>> connection.Test1(param1=1)["test"]["bar"], "boom")
>>> self.assertEqual(
>>> connection.Test2(param1="foo")["test"], "foo")
>>> self.assertEqual(
>>> connection.Test3(param1=6)["test"], 12)
>>> self.assertEqual(
>>> connection.Test3(param1=6)["bar"], 42)
So here's the flow, bestie, pay attention πΈ First you define a sample class that gets passed to your decorator mock.mockedservice. Then a service gets initialized and launched automatically β automatic, we love a self-starting queen β¨ β and after that you just connect your client to him, establish your connection, and now you can call your methods and it will give you the expected result. Easy.
You can also mock some types too, which helps you mock more complex services and interfaces β podman, for example π
And plot twist: you can define the return type by using the method docstring, like the method Test1 in our previous example. Iconic.
β οΈ Heads up: the mocking module is only compatible with python 3 or higher version of python, because this module requires annotation to generate the interface description. If you try to use it with python 2.x it will raise an ImportError. That's not a vibe, so don't.
π INDICES AND TABLES π
- Index <>
- Module Index <>
- Search Page <>
π Author
Harald Hoyer<harald@redhat.com>, Lars Karlitski<lars@karlitski.net>
Β©οΈ Copyright
2018, Harald Hoyer<harald@redhat.com>, Lars Karlitski<lars@karlitski.net>
and that's the whole page, bestie, we ate and left no crumbs π«Ά this lil beauty is dated Jul 05, 2026 and answers to the name VARLINK(1) β go forth and mock responsibly π
π¦ where this page comes from
- ubuntu stonking: python3-varlink 32.1.0-2 Β· Apache-2.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms