11import os
22from concurrent .futures import ProcessPoolExecutor
3+ from functools import cached_property
34from multiprocessing import Process
45from multiprocessing .context import BaseContext
56from pathlib import Path
1011import pystemd .cutils
1112import pystemd .run
1213import pystemd .utils
14+ from pystemd .dbuslib import DBus
1315
1416
1517class TransientUnitContext (BaseContext ):
@@ -24,10 +26,12 @@ def __init__(
2426 properties : Dict [str , Any ],
2527 main_process : Sequence [str ] = (),
2628 user_mode : bool = False ,
29+ unit_name : Optional [str ] = None ,
2730 ) -> None :
2831 self .unit : Optional [pystemd .systemd1 .Unit ] = None
2932 self .properties = properties
3033 self .user_mode = user_mode
34+ self .unit_name = unit_name
3135 self .main_process_cmd = main_process or [
3236 "/bin/bash" ,
3337 "-c" ,
@@ -39,6 +43,7 @@ def start_unit(self) -> pystemd.systemd1.Unit:
3943 assert self .unit is None , "Unit already started"
4044 self .unit = pystemd .run (
4145 self .main_process_cmd ,
46+ name = self .unit_name ,
4247 user_mode = self .user_mode ,
4348 extra = {
4449 ** self .properties ,
@@ -121,17 +126,25 @@ class TransientUnitProcess(_ProcessWithPreRun):
121126 the unit will finish.
122127 """
123128
124- def __init__ (self , * , properties = None , user_mode = False , ** kwargs ) -> None :
129+ def __init__ (self , * , properties = None , user_mode = False , unit_name = None , ** kwargs ) -> None :
125130 super ().__init__ (** kwargs )
126131 self .user_mode = user_mode
132+ self .unit_name = unit_name or pystemd .utils .random_unit_name (prefix = "pystemd-future-" )
127133 self .properties = {
128134 pystemd .utils .x2char_star (k ): v for k , v in (properties or {}).items ()
129135 }
130136
137+ @cached_property
138+ def unit (self ):
139+ bus = DBus (user_mode = self .user_mode )
140+ bus .__enter__ ()
141+ return pystemd .systemd1 .Unit (self .unit_name , bus , _autoload = True )
142+
131143 def pre_run (self ):
132144 context = TransientUnitContext (
133145 properties = self .properties ,
134146 user_mode = self .user_mode ,
147+ unit_name = self .unit_name ,
135148 main_process = [
136149 "/bin/bash" ,
137150 "-c" ,
0 commit comments