Debian Codegraph @

scripts/dogtail-run-headless-next

raw
1 #!/usr/bin/python3
2 # -*- coding: utf-8 -*-
3 from __future__ import absolute_import, division, print_function, unicode_literals
4 import argparse
5 import sys
6 import os
7 import glob
8 import subprocess
9 import time
10 import shutil
11 import re
12 try:
13 import configparser
14 except ImportError:
15 import ConfigParser as configparser
16
17 from dogtail.sessions import Script
18
19 SCRIPT_DESCRIPTION = """
20 Unlike the original headless script this will make use of a Display Manager
21 (DM) to handle starting the X server and user session. It's motivated by
22 changes related to systemd that disallows running a GNOME session from an
23 environment spawned by 'su'. The original headless will not work in these
24 cases on systemd systems.
25
26 This version uses the AutoLogin feature of the DM, so that when its
27 service is started the session will login for the user immediately. It then
28 grabs the new session’s environment and runs the target script in there.
29
30 Works on distros where 'service gdm/kdm/lightdm start/stop' takes effect,
31 and on systemd systems using systemd-logind.
32 """
33
34 PRESERVE_ENVS = ["PYTHONPATH", "TEST"]
35
36
37 def getSessionEnvironment(sessionBinary):
38 def isSessionProcess(file_name):
39 session_binary_path = ("/usr/bin/plasma-desktop"
40 if sessionBinary.split("/")[-1] == "startkde"
41 else sessionBinary)
42 try:
43 if os.path.realpath(file_name + "exe") != session_binary_path:
44 return False
45 except OSError:
46 return False
47 pid = file_name.split("/")[2]
48 if pid == "self" or pid == str(os.getpid()):
49 return False
50 return True
51
52 def get_environment_dictionary(file_name):
53 try:
54 data = open(file_name, "r").read()
55 except IOError as e:
56 print("dogtail exception:", e)
57 return {}
58 items = data.split("\x00")
59 env = {}
60 for item in items:
61 if "=" not in item:
62 continue
63 k, v = item.split("=", 1)
64 env[k] = v
65 return env
66
67 def copy_environment_variables(env_dict):
68 for var in PRESERVE_ENVS:
69 if var in os.environ:
70 env_dict[var] = os.environ[var]
71 return env_dict
72
73 env = None
74 for path in glob.glob("/proc/*/"):
75 if not isSessionProcess(path):
76 continue
77 env = get_environment_dictionary(path + "environ")
78
79 if not env:
80 raise RuntimeError("Can't find our environment!")
81 return copy_environment_variables(env)
82
83
84 def execCodeWithEnv(code, env=None):
85 with open("/tmp/execcode.dogtail", "w") as f:
86 f.write(code)
87 subprocess.Popen(
88 "python /tmp/execcode.dogtail".split(),
89 env=(os.environ if env is None else env)
90 ).wait()
91
92
93 ### qecore headless code to quickfix EL9 #####################
94 ENVIRONMENT_DICTIONARY = {}
95 ENVIRONMENT_VARIABLES_TO_PRESERVE = ["PYTHONPATH", "TEST", "TERM"]
96
97
98 def run(command, verbose=False):
99 try:
100 out = subprocess.check_output(
101 command, shell=True, stderr=subprocess.STDOUT, encoding="utf-8"
102 )
103 return out if not verbose else (out, 0, None)
104 except subprocess.CalledProcessError as e:
105 return e.output if not verbose else (e.output, e.returncode, e)
106
107
108 def _get_environment_as_dictionary(path_to_process):
109 def is_session_process(p):
110 pid = p.split("/")[2]
111 return pid != "self" and pid != str(os.getpid())
112
113 if not is_session_process(path_to_process):
114 return False
115
116 file_name = path_to_process + "environ"
117 try:
118 data = open(file_name, "r").read()
119 except IOError:
120 return False
121
122 for item in data.split("\x00"):
123 if "=" in item:
124 k, v = item.split("=", 1)
125 ENVIRONMENT_DICTIONARY[k] = v
126
127 for var in ENVIRONMENT_VARIABLES_TO_PRESERVE:
128 if var in os.environ:
129 ENVIRONMENT_DICTIONARY[var] = os.environ[var]
130
131 return True
132
133
134 def get_environment_dictionary(session_binary):
135 def get_gs_pid():
136 out = run("ps o pid,command,user").split("\n")
137 for line in out:
138 if "gnome-session" in line and os.getenv("USER", "") in line:
139 return int(line.strip().split()[0])
140
141 pid = get_gs_pid()
142 if pid:
143 _get_environment_as_dictionary(f"/proc/{pid}/")
144 print("headless: Setting environment variable TERM as 'xterm'")
145 ENVIRONMENT_DICTIONARY["TERM"] = "xterm"
146 return ENVIRONMENT_DICTIONARY
147
148 status = run("systemctl is-active gdm").strip()
149 print(
150 f"headless: Display Manager Status is '{status}'\n"
151 "headless: Can't find our environment!\n"
152 "headless: Stopping Display Manager"
153 )
154 subprocess.Popen("sudo systemctl stop gdm".split()).wait()
155 sys.exit(1)
156
157
158 ###################################
159
160
161 class DisplayManagerSession:
162 gdm_config = "/etc/gdm/custom.conf"
163 kdm_config = "/etc/kde/kdm/kdmrc"
164 lightdm_config = "/etc/lightdm/lightdm.conf"
165
166 gdm_options = {
167 "section": "daemon",
168 "enable": "AutomaticLoginEnable",
169 "user": "AutomaticLogin"
170 }
171 kdm_options = {
172 "section": "X-:0-Core",
173 "enable": "AutoLoginEnable",
174 "user": "AutoLoginUser"
175 }
176 lightdm_options = {
177 "section": "Seat:*",
178 "user": "autologin-user",
179 "timeout": "autologin-user-timeout",
180 "session": "autologin-session"
181 }
182
183 def __init__(self, display_manager="gdm", session="gnome",
184 session_binary="gnome-shell", user=None):
185 self.display_manager = display_manager
186 self.session = session
187 self.session_binary = session_binary
188 self.user = user or os.getenv("USER", "test")
189 self.accountfile = f"/var/lib/AccountsService/users/{self.user}"
190
191 if display_manager == "gdm":
192 self.config = self.gdm_config
193 self.options = self.gdm_options
194 elif display_manager == "kdm":
195 self.config = self.kdm_config
196 self.options = self.kdm_options
197 elif display_manager == "lightdm":
198 self.config = self.lightdm_config
199 self.options = self.lightdm_options
200 else:
201 raise ValueError(f"Unsupported display manager: {display_manager}")
202
203 self.tmp_file = "/tmp/" + os.path.basename(self.config)
204
205 def isProcessRunning(self, proc_name):
206 ps = subprocess.Popen(["ps", "axw"], stdout=subprocess.PIPE)
207 for line in ps.stdout:
208 if "headless" in line.decode("utf-8"):
209 continue
210 if re.search(proc_name, line.decode("utf-8")):
211 return True
212 return False
213
214 def waitForProcess(self, proc_name, invert=False, max_cycles=None):
215 """
216 Wait until a process appears (invert=False) or disappears (invert=True).
217
218 :param proc_name: substring of the process name to wait for
219 :param invert: if False, wait until process **is** running; if True, wait until it's gone
220 :param max_cycles: optional int, maximum number of 1-second polls before timing out;
221 None means wait indefinitely
222 :return: True if the desired condition was met within the limit, False on timeout
223 """
224 cycles = 0
225 # keep looping while condition is not yet met
226 while self.isProcessRunning(proc_name) is invert:
227 # if we've reached the cycle limit, bail out
228 if max_cycles is not None and cycles >= max_cycles:
229 return False
230 time.sleep(1)
231 cycles += 1
232 return True
233
234
235 def setup(self, restore=False, force_xorg=False):
236 # copy and edit config
237 shutil.copy(self.config, self.tmp_file)
238 if hasattr(configparser, "SafeConfigParser"):
239 cfg = configparser.SafeConfigParser()
240 else:
241 cfg = configparser.ConfigParser()
242 cfg.optionxform = str
243 cfg.read(self.tmp_file)
244
245 section = self.options["section"]
246 if not cfg.has_section(section):
247 cfg.add_section(section)
248
249 if not restore:
250 if self.display_manager in ("gdm", "kdm"):
251 cfg.set(section, self.options["enable"], "true")
252 cfg.set(section, self.options["user"], self.user)
253 if force_xorg and self.display_manager == "gdm":
254 cfg.set(section, "WaylandEnable", "false")
255 else: # lightdm
256 cfg.set(section, self.options["user"], self.user)
257 cfg.set(section, self.options["timeout"], "0")
258 if self.session:
259 cfg.set(section, self.options["session"], self.session)
260 else:
261 if self.display_manager in ("gdm", "kdm"):
262 cfg.remove_option(section, self.options["enable"])
263 cfg.remove_option(section, self.options["user"])
264 else:
265 for key in ("user", "timeout", "session"):
266 cfg.remove_option(section, self.options[key])
267
268 with open(self.tmp_file, "w") as out:
269 cfg.write(out)
270 subprocess.Popen(f"sudo mv -f {self.tmp_file} {self.config}", shell=True).wait()
271
272 # post-setup for GDM/KDM only
273 if not restore and self.display_manager in ("gdm", "kdm"):
274 if "kwin" in self.session_binary:
275 try:
276 os.makedirs(os.path.expanduser("~/.kde/env/"), exist_ok=True)
277 except Exception:
278 pass
279 subprocess.Popen(
280 "echo 'export QT_ACCESSIBILITY=1' > ~/.kde/env/qt-at-spi.sh",
281 shell=True
282 ).wait()
283
284 if self.display_manager == "gdm":
285 need_restart = False
286 tmp_acc = f"/tmp/{self.user}_headless"
287 if os.path.isfile(self.accountfile):
288 subprocess.Popen(
289 f"cp -f {self.accountfile} {tmp_acc}", shell=True
290 ).wait()
291
292 if hasattr(configparser, "SafeConfigParser"):
293 acc_cfg = configparser.SafeConfigParser()
294 else:
295 acc_cfg = configparser.ConfigParser()
296 acc_cfg.optionxform = str
297 acc_cfg.read(tmp_acc)
298
299 try:
300 saved = acc_cfg.get("User", "Session")
301 if self.session is None:
302 if "kde" in saved and "gnome-shell" in self.session_binary:
303 self.session_binary = "/usr/bin/kwin"
304 elif "gnome" in saved and "kwin" in self.session_binary:
305 self.session_binary = "/usr/bin/gnome-shell"
306 elif saved != self.session:
307 acc_cfg.set("User", "Session", self.session)
308 need_restart = True
309 except (configparser.NoOptionError, configparser.NoSectionError):
310 if self.session is not None:
311 if not acc_cfg.has_section("User"):
312 acc_cfg.add_section("User")
313 acc_cfg.set("User", "Session", self.session)
314 acc_cfg.set("User", "SystemAccount", "false")
315 need_restart = True
316
317 if need_restart:
318 with open(tmp_acc, "w") as o:
319 acc_cfg.write(o)
320 subprocess.Popen(
321 f"sudo mv -f {tmp_acc} {self.accountfile}", shell=True
322 ).wait()
323 time.sleep(1)
324 subprocess.Popen(
325 "sudo systemctl restart accounts-daemon", shell=True
326 ).wait()
327 time.sleep(1)
328 subprocess.Popen(
329 "sudo systemctl restart systemd-logind", shell=True
330 ).wait()
331 time.sleep(1)
332 else:
333 subprocess.Popen(f"sudo rm -f {tmp_acc}", shell=True).wait()
334
335 elif self.display_manager == "kdm":
336 if self.session is not None:
337 subprocess.Popen(
338 f"echo '[Desktop]\nSession={self.session}' > /home/{self.user}/.dmrc",
339 shell=True
340 ).wait()
341
342 def start(self, restart=False):
343 subprocess.Popen(f"sudo systemctl stop {self.display_manager}".split())
344 time.sleep(0.5)
345
346 # kill any pre-existing seat0 session for this user
347 if os.system(
348 f"sudo loginctl | grep {self.user} | grep seat0"
349 ) == 0:
350 subprocess.Popen(
351 f"sudo loginctl kill-session --signal=9 $(loginctl | grep {self.user} | grep seat0 | awk '{{print $1}}')",
352 shell=True
353 ).wait()
354 time.sleep(5)
355
356 subprocess.Popen(f"sudo systemctl start {self.display_manager}".split())
357 self.waitForProcess(os.path.basename(self.session_binary))
358
359 # give DM-specific delay
360 if self.display_manager == "kdm":
361 time.sleep(10)
362 elif self.display_manager == "gdm":
363 time.sleep(4)
364
365 def set_accessibility_to(self, enable):
366 subprocess.Popen(
367 f"/usr/bin/gsettings set org.gnome.desktop.interface toolkit-accessibility {'true' if enable else 'false'}",
368 shell=True,
369 env=os.environ
370 )
371
372 def stop(self):
373 subprocess.Popen(
374 f"sudo systemctl stop {self.display_manager}".split()
375 ).wait()
376 self.waitForProcess(self.display_manager, invert=True)
377 time.sleep(3)
378
379 # if session processes linger, force-kill them
380 if self.isProcessRunning(os.path.basename(self.session_binary)):
381 subprocess.Popen(
382 f"sudo loginctl terminate-session $(loginctl | grep {self.user} | grep seat0 | awk '{{print $1}}')",
383 shell=True
384 ).wait()
385 time.sleep(5)
386
387 if any(self.isProcessRunning(n) for n in ("Xorg", "gnome-shell", "Xwayland")):
388 subprocess.Popen(
389 f"sudo loginctl kill-session --signal=9 $(loginctl | grep {self.user} | grep seat0 | awk '{{print $1}}')",
390 shell=True
391 ).wait()
392 time.sleep(3)
393
394
395 def parse():
396 parser = argparse.ArgumentParser(
397 prog="$ dogtail-run-headless-next",
398 description=SCRIPT_DESCRIPTION,
399 formatter_class=argparse.RawDescriptionHelpFormatter
400 )
401
402 parser.add_argument("script",
403 help="Command to execute in the headless session")
404
405 parser.add_argument("--session",
406 required=False,
407 help="\n".join((
408 "What session to use (e.g. 'gnome', 'kde-plasma', 'mate').",
409 "Comes from /usr/share/xsessions/ or /usr/share/wayland-sessions/."
410 )))
411
412 parser.add_argument("--session-binary",
413 required=False,
414 help="Full path to an in-session binary (e.g. '/usr/bin/gnome-shell').")
415
416 parser.add_argument("--dm",
417 required=False,
418 help="\n".join((
419 "What display manager to use for spawning session.",
420 "Supported: 'gdm' (default), 'kdm', or 'lightdm'."
421 )))
422
423 parser.add_argument("--restart",
424 action="store_true",
425 help="Restart previously running display manager session before script execution.")
426
427 parser.add_argument("--dont-start",
428 action="store_true",
429 help="Use already running session (doesn't have to be under Display Manager).")
430
431 parser.add_argument("--dont-kill",
432 action="store_true",
433 help="Do not kill session when script exits.")
434
435 parser.add_argument("--disable-a11y",
436 action="store_true",
437 help="Disable accessibility technologies on exit.")
438
439 parser.add_argument("--debug",
440 action="store_true",
441 help="Enable DOGTAIL_DEBUG in the session environment.")
442
443 parser.add_argument("--force-xorg",
444 action="store_true",
445 help="Force Xorg session by setting WaylandEnable=false in GDM config.")
446
447 return parser.parse_args()
448
449
450 def main():
451 args = parse()
452 script_command_list = args.script.split()
453
454 # default session / binary logic
455 if args.dm == "lightdm":
456 args.session = args.session or "mate"
457 args.session_binary = args.session_binary or "/usr/bin/mate-session"
458 elif args.session is None or "gnome" in args.session:
459 args.session_binary = args.session_binary or "/usr/bin/gnome-session"
460 elif "kde" in args.session:
461 args.session_binary = args.session_binary or "/usr/bin/kwin"
462 if args.session == "kde":
463 args.session = "kde-plasma"
464 else:
465 if not args.session_binary:
466 print("dogtail-run-headless-next: Need to specify --session-binary for '%s'." %
467 args.session)
468 sys.exit(-1)
469
470 # pick display manager
471 if args.dm in (None, "gdm"):
472 display_manager_name = "gdm"
473 elif args.dm == "kdm":
474 display_manager_name = "kdm"
475 elif args.dm == "lightdm":
476 display_manager_name = "lightdm"
477 else:
478 print("dogtail-run-headless-next: Unknown display manager '%s'!" % args.dm)
479 sys.exit(-1)
480
481 print("dogtail-run-headless-next: Using display manager:", display_manager_name)
482 display_manager_session = DisplayManagerSession(
483 display_manager_name,
484 args.session,
485 args.session_binary,
486 user=os.getenv("USER")
487 )
488
489 if not args.dont_start:
490 display_manager_session.setup(force_xorg=args.force_xorg)
491 display_manager_session.start(restart=args.restart)
492
493 print("dogtail-run-headless-next: Binding to session binary:",
494 display_manager_session.session_binary)
495
496 # grab the session environment
497 try:
498 os.environ = getSessionEnvironment(
499 display_manager_session.session_binary
500 )
501 except RuntimeError:
502 print("Could not get environment from initial session binary",
503 display_manager_session.session_binary)
504 if display_manager_session.session_binary == "/usr/bin/gnome-shell":
505 try:
506 binary = "/usr/libexec/gvfsd"
507 try:
508 with open('/etc/redhat-release', 'r') as f:
509 release = f.read()
510 if "Linux release 9" in release:
511 binary = "/usr/bin/gnome-session"
512 except Exception:
513 pass
514 print("Try fallback binary:", binary)
515 os.environ = getSessionEnvironment(binary)
516 print("dogtail-run-headless-next: Trying workaround with", binary)
517 except RuntimeError:
518 print("dogtail-run-headless-next: Fallback failed for gvfsd")
519 display_manager_session.stop()
520 display_manager_session.setup(restore=True)
521 sys.exit(1)
522 else:
523 display_manager_session.stop()
524 display_manager_session.setup(restore=True)
525 sys.exit(1)
526
527 if args.debug:
528 os.environ["DOGTAIL_DEBUG"] = "true"
529
530 if display_manager_name == "gdm":
531 display_manager_session.set_accessibility_to(True)
532
533 script = Script(script_command_list)
534
535 if os.path.isfile('/tmp/headless_enable_fatal_criticals'):
536 os.environ['G_DEBUG'] = 'fatal-criticals'
537 if os.path.isfile('/tmp/headless_enable_fatal_warnings'):
538 os.environ['G_DEBUG'] = 'fatal-warnings'
539
540 pid = script.start()
541 print("dogtail-run-headless-next: Started script with PID", pid)
542 exit_code = script.wait()
543 print("dogtail-run-headless-next: Script finished with return code", exit_code)
544
545 if args.disable_a11y:
546 display_manager_session.set_accessibility_to(False)
547
548 if not args.dont_kill:
549 display_manager_session.stop()
550 display_manager_session.setup(restore=True)
551
552 sys.exit(exit_code)
553
554
555 if __name__ == "__main__":
556 main()