File: dogtail-run-headless-next

package info (click to toggle)
dogtail 1.0.7-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,240 kB
  • sloc: python: 6,124; makefile: 56; sh: 7
file content (556 lines) | stat: -rwxr-xr-x 20,510 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import argparse
import sys
import os
import glob
import subprocess
import time
import shutil
import re
try:
    import configparser
except ImportError:
    import ConfigParser as configparser

from dogtail.sessions import Script

SCRIPT_DESCRIPTION = """
Unlike the original headless script this will make use of a Display Manager
(DM) to handle starting the X server and user session. It's motivated by
changes related to systemd that disallows running a GNOME session from an
environment spawned by 'su'. The original headless will not work in these
cases on systemd systems.

This version uses the AutoLogin feature of the DM, so that when its
service is started the session will login for the user immediately. It then
grabs the new session’s environment and runs the target script in there.

Works on distros where 'service gdm/kdm/lightdm start/stop' takes effect,
and on systemd systems using systemd-logind.
"""

PRESERVE_ENVS = ["PYTHONPATH", "TEST"]


def getSessionEnvironment(sessionBinary):
    def isSessionProcess(file_name):
        session_binary_path = ("/usr/bin/plasma-desktop"
                               if sessionBinary.split("/")[-1] == "startkde"
                               else sessionBinary)
        try:
            if os.path.realpath(file_name + "exe") != session_binary_path:
                return False
        except OSError:
            return False
        pid = file_name.split("/")[2]
        if pid == "self" or pid == str(os.getpid()):
            return False
        return True

    def get_environment_dictionary(file_name):
        try:
            data = open(file_name, "r").read()
        except IOError as e:
            print("dogtail exception:", e)
            return {}
        items = data.split("\x00")
        env = {}
        for item in items:
            if "=" not in item:
                continue
            k, v = item.split("=", 1)
            env[k] = v
        return env

    def copy_environment_variables(env_dict):
        for var in PRESERVE_ENVS:
            if var in os.environ:
                env_dict[var] = os.environ[var]
        return env_dict

    env = None
    for path in glob.glob("/proc/*/"):
        if not isSessionProcess(path):
            continue
        env = get_environment_dictionary(path + "environ")

    if not env:
        raise RuntimeError("Can't find our environment!")
    return copy_environment_variables(env)


def execCodeWithEnv(code, env=None):
    with open("/tmp/execcode.dogtail", "w") as f:
        f.write(code)
    subprocess.Popen(
        "python /tmp/execcode.dogtail".split(),
        env=(os.environ if env is None else env)
    ).wait()


### qecore headless code to quickfix EL9 #####################
ENVIRONMENT_DICTIONARY = {}
ENVIRONMENT_VARIABLES_TO_PRESERVE = ["PYTHONPATH", "TEST", "TERM"]


def run(command, verbose=False):
    try:
        out = subprocess.check_output(
            command, shell=True, stderr=subprocess.STDOUT, encoding="utf-8"
        )
        return out if not verbose else (out, 0, None)
    except subprocess.CalledProcessError as e:
        return e.output if not verbose else (e.output, e.returncode, e)


def _get_environment_as_dictionary(path_to_process):
    def is_session_process(p):
        pid = p.split("/")[2]
        return pid != "self" and pid != str(os.getpid())

    if not is_session_process(path_to_process):
        return False

    file_name = path_to_process + "environ"
    try:
        data = open(file_name, "r").read()
    except IOError:
        return False

    for item in data.split("\x00"):
        if "=" in item:
            k, v = item.split("=", 1)
            ENVIRONMENT_DICTIONARY[k] = v

    for var in ENVIRONMENT_VARIABLES_TO_PRESERVE:
        if var in os.environ:
            ENVIRONMENT_DICTIONARY[var] = os.environ[var]

    return True


def get_environment_dictionary(session_binary):
    def get_gs_pid():
        out = run("ps o pid,command,user").split("\n")
        for line in out:
            if "gnome-session" in line and os.getenv("USER", "") in line:
                return int(line.strip().split()[0])

    pid = get_gs_pid()
    if pid:
        _get_environment_as_dictionary(f"/proc/{pid}/")
        print("headless: Setting environment variable TERM as 'xterm'")
        ENVIRONMENT_DICTIONARY["TERM"] = "xterm"
        return ENVIRONMENT_DICTIONARY

    status = run("systemctl is-active gdm").strip()
    print(
        f"headless: Display Manager Status is '{status}'\n"
        "headless: Can't find our environment!\n"
        "headless: Stopping Display Manager"
    )
    subprocess.Popen("sudo systemctl stop gdm".split()).wait()
    sys.exit(1)


###################################


class DisplayManagerSession:
    gdm_config     = "/etc/gdm/custom.conf"
    kdm_config     = "/etc/kde/kdm/kdmrc"
    lightdm_config = "/etc/lightdm/lightdm.conf"

    gdm_options = {
        "section": "daemon",
        "enable":  "AutomaticLoginEnable",
        "user":    "AutomaticLogin"
    }
    kdm_options = {
        "section": "X-:0-Core",
        "enable":  "AutoLoginEnable",
        "user":    "AutoLoginUser"
    }
    lightdm_options = {
        "section": "Seat:*",
        "user":    "autologin-user",
        "timeout": "autologin-user-timeout",
        "session": "autologin-session"
    }

    def __init__(self, display_manager="gdm", session="gnome",
                 session_binary="gnome-shell", user=None):
        self.display_manager = display_manager
        self.session         = session
        self.session_binary  = session_binary
        self.user            = user or os.getenv("USER", "test")
        self.accountfile     = f"/var/lib/AccountsService/users/{self.user}"

        if display_manager == "gdm":
            self.config = self.gdm_config
            self.options = self.gdm_options
        elif display_manager == "kdm":
            self.config = self.kdm_config
            self.options = self.kdm_options
        elif display_manager == "lightdm":
            self.config = self.lightdm_config
            self.options = self.lightdm_options
        else:
            raise ValueError(f"Unsupported display manager: {display_manager}")

        self.tmp_file = "/tmp/" + os.path.basename(self.config)

    def isProcessRunning(self, proc_name):
        ps = subprocess.Popen(["ps", "axw"], stdout=subprocess.PIPE)
        for line in ps.stdout:
            if "headless" in line.decode("utf-8"):
                continue
            if re.search(proc_name, line.decode("utf-8")):
                return True
        return False

    def waitForProcess(self, proc_name, invert=False, max_cycles=None):
        """
        Wait until a process appears (invert=False) or disappears (invert=True).

        :param proc_name: substring of the process name to wait for
        :param invert: if False, wait until process **is** running; if True, wait until it's gone
        :param max_cycles: optional int, maximum number of 1-second polls before timing out;
                           None means wait indefinitely
        :return: True if the desired condition was met within the limit, False on timeout
        """
        cycles = 0
        # keep looping while condition is not yet met
        while self.isProcessRunning(proc_name) is invert:
            # if we've reached the cycle limit, bail out
            if max_cycles is not None and cycles >= max_cycles:
                return False
            time.sleep(1)
            cycles += 1
        return True


    def setup(self, restore=False, force_xorg=False):
        # copy and edit config
        shutil.copy(self.config, self.tmp_file)
        if hasattr(configparser, "SafeConfigParser"):
            cfg = configparser.SafeConfigParser()
        else:
            cfg = configparser.ConfigParser()
        cfg.optionxform = str
        cfg.read(self.tmp_file)

        section = self.options["section"]
        if not cfg.has_section(section):
            cfg.add_section(section)

        if not restore:
            if self.display_manager in ("gdm", "kdm"):
                cfg.set(section, self.options["enable"], "true")
                cfg.set(section, self.options["user"], self.user)
                if force_xorg and self.display_manager == "gdm":
                    cfg.set(section, "WaylandEnable", "false")
            else:  # lightdm
                cfg.set(section, self.options["user"], self.user)
                cfg.set(section, self.options["timeout"], "0")
                if self.session:
                    cfg.set(section, self.options["session"], self.session)
        else:
            if self.display_manager in ("gdm", "kdm"):
                cfg.remove_option(section, self.options["enable"])
                cfg.remove_option(section, self.options["user"])
            else:
                for key in ("user", "timeout", "session"):
                    cfg.remove_option(section, self.options[key])

        with open(self.tmp_file, "w") as out:
            cfg.write(out)
        subprocess.Popen(f"sudo mv -f {self.tmp_file} {self.config}", shell=True).wait()

        # post-setup for GDM/KDM only
        if not restore and self.display_manager in ("gdm", "kdm"):
            if "kwin" in self.session_binary:
                try:
                    os.makedirs(os.path.expanduser("~/.kde/env/"), exist_ok=True)
                except Exception:
                    pass
                subprocess.Popen(
                    "echo 'export QT_ACCESSIBILITY=1' > ~/.kde/env/qt-at-spi.sh",
                    shell=True
                ).wait()

            if self.display_manager == "gdm":
                need_restart = False
                tmp_acc = f"/tmp/{self.user}_headless"
                if os.path.isfile(self.accountfile):
                    subprocess.Popen(
                        f"cp -f {self.accountfile} {tmp_acc}", shell=True
                    ).wait()

                if hasattr(configparser, "SafeConfigParser"):
                    acc_cfg = configparser.SafeConfigParser()
                else:
                    acc_cfg = configparser.ConfigParser()
                acc_cfg.optionxform = str
                acc_cfg.read(tmp_acc)

                try:
                    saved = acc_cfg.get("User", "Session")
                    if self.session is None:
                        if "kde" in saved and "gnome-shell" in self.session_binary:
                            self.session_binary = "/usr/bin/kwin"
                        elif "gnome" in saved and "kwin" in self.session_binary:
                            self.session_binary = "/usr/bin/gnome-shell"
                    elif saved != self.session:
                        acc_cfg.set("User", "Session", self.session)
                        need_restart = True
                except (configparser.NoOptionError, configparser.NoSectionError):
                    if self.session is not None:
                        if not acc_cfg.has_section("User"):
                            acc_cfg.add_section("User")
                        acc_cfg.set("User", "Session", self.session)
                        acc_cfg.set("User", "SystemAccount", "false")
                        need_restart = True

                if need_restart:
                    with open(tmp_acc, "w") as o:
                        acc_cfg.write(o)
                    subprocess.Popen(
                        f"sudo mv -f {tmp_acc} {self.accountfile}", shell=True
                    ).wait()
                    time.sleep(1)
                    subprocess.Popen(
                        "sudo systemctl restart accounts-daemon", shell=True
                    ).wait()
                    time.sleep(1)
                    subprocess.Popen(
                        "sudo systemctl restart systemd-logind", shell=True
                    ).wait()
                    time.sleep(1)
                else:
                    subprocess.Popen(f"sudo rm -f {tmp_acc}", shell=True).wait()

            elif self.display_manager == "kdm":
                if self.session is not None:
                    subprocess.Popen(
                        f"echo '[Desktop]\nSession={self.session}' > /home/{self.user}/.dmrc",
                        shell=True
                    ).wait()

    def start(self, restart=False):
        subprocess.Popen(f"sudo systemctl stop {self.display_manager}".split())
        time.sleep(0.5)

        # kill any pre-existing seat0 session for this user
        if os.system(
            f"sudo loginctl | grep {self.user} | grep seat0"
        ) == 0:
            subprocess.Popen(
                f"sudo loginctl kill-session --signal=9 $(loginctl | grep {self.user} | grep seat0 | awk '{{print $1}}')",
                shell=True
            ).wait()
            time.sleep(5)

        subprocess.Popen(f"sudo systemctl start {self.display_manager}".split())
        self.waitForProcess(os.path.basename(self.session_binary))

        # give DM-specific delay
        if self.display_manager == "kdm":
            time.sleep(10)
        elif self.display_manager == "gdm":
            time.sleep(4)

    def set_accessibility_to(self, enable):
        subprocess.Popen(
            f"/usr/bin/gsettings set org.gnome.desktop.interface toolkit-accessibility {'true' if enable else 'false'}",
            shell=True,
            env=os.environ
        )

    def stop(self):
        subprocess.Popen(
            f"sudo systemctl stop {self.display_manager}".split()
        ).wait()
        self.waitForProcess(self.display_manager, invert=True)
        time.sleep(3)

        # if session processes linger, force-kill them
        if self.isProcessRunning(os.path.basename(self.session_binary)):
            subprocess.Popen(
                f"sudo loginctl terminate-session $(loginctl | grep {self.user} | grep seat0 | awk '{{print $1}}')",
                shell=True
            ).wait()
            time.sleep(5)

        if any(self.isProcessRunning(n) for n in ("Xorg", "gnome-shell", "Xwayland")):
            subprocess.Popen(
                f"sudo loginctl kill-session --signal=9 $(loginctl | grep {self.user} | grep seat0 | awk '{{print $1}}')",
                shell=True
            ).wait()
            time.sleep(3)


def parse():
    parser = argparse.ArgumentParser(
        prog="$ dogtail-run-headless-next",
        description=SCRIPT_DESCRIPTION,
        formatter_class=argparse.RawDescriptionHelpFormatter
    )

    parser.add_argument("script",
                        help="Command to execute in the headless session")

    parser.add_argument("--session",
                        required=False,
                        help="\n".join((
                            "What session to use (e.g. 'gnome', 'kde-plasma', 'mate').",
                            "Comes from /usr/share/xsessions/ or /usr/share/wayland-sessions/."
                        )))

    parser.add_argument("--session-binary",
                        required=False,
                        help="Full path to an in-session binary (e.g. '/usr/bin/gnome-shell').")

    parser.add_argument("--dm",
                        required=False,
                        help="\n".join((
                            "What display manager to use for spawning session.",
                            "Supported: 'gdm' (default), 'kdm', or 'lightdm'."
                        )))

    parser.add_argument("--restart",
                        action="store_true",
                        help="Restart previously running display manager session before script execution.")

    parser.add_argument("--dont-start",
                        action="store_true",
                        help="Use already running session (doesn't have to be under Display Manager).")

    parser.add_argument("--dont-kill",
                        action="store_true",
                        help="Do not kill session when script exits.")

    parser.add_argument("--disable-a11y",
                        action="store_true",
                        help="Disable accessibility technologies on exit.")

    parser.add_argument("--debug",
                        action="store_true",
                        help="Enable DOGTAIL_DEBUG in the session environment.")

    parser.add_argument("--force-xorg",
                        action="store_true",
                        help="Force Xorg session by setting WaylandEnable=false in GDM config.")

    return parser.parse_args()


def main():
    args = parse()
    script_command_list = args.script.split()

    # default session / binary logic
    if args.dm == "lightdm":
        args.session = args.session or "mate"
        args.session_binary = args.session_binary or "/usr/bin/mate-session"
    elif args.session is None or "gnome" in args.session:
        args.session_binary = args.session_binary or "/usr/bin/gnome-session"
    elif "kde" in args.session:
        args.session_binary = args.session_binary or "/usr/bin/kwin"
        if args.session == "kde":
            args.session = "kde-plasma"
    else:
        if not args.session_binary:
            print("dogtail-run-headless-next: Need to specify --session-binary for '%s'." %
                  args.session)
            sys.exit(-1)

    # pick display manager
    if args.dm in (None, "gdm"):
        display_manager_name = "gdm"
    elif args.dm == "kdm":
        display_manager_name = "kdm"
    elif args.dm == "lightdm":
        display_manager_name = "lightdm"
    else:
        print("dogtail-run-headless-next: Unknown display manager '%s'!" % args.dm)
        sys.exit(-1)

    print("dogtail-run-headless-next: Using display manager:", display_manager_name)
    display_manager_session = DisplayManagerSession(
        display_manager_name,
        args.session,
        args.session_binary,
        user=os.getenv("USER")
    )

    if not args.dont_start:
        display_manager_session.setup(force_xorg=args.force_xorg)
        display_manager_session.start(restart=args.restart)

    print("dogtail-run-headless-next: Binding to session binary:",
          display_manager_session.session_binary)

    # grab the session environment
    try:
        os.environ = getSessionEnvironment(
            display_manager_session.session_binary
        )
    except RuntimeError:
        print("Could not get environment from initial session binary",
              display_manager_session.session_binary)
        if display_manager_session.session_binary == "/usr/bin/gnome-shell":
            try:
                binary = "/usr/libexec/gvfsd"
                try:
                    with open('/etc/redhat-release', 'r') as f:
                        release = f.read()
                    if "Linux release 9" in release:
                        binary = "/usr/bin/gnome-session"
                except Exception:
                    pass
                print("Try fallback binary:", binary)
                os.environ = getSessionEnvironment(binary)
                print("dogtail-run-headless-next: Trying workaround with", binary)
            except RuntimeError:
                print("dogtail-run-headless-next: Fallback failed for gvfsd")
                display_manager_session.stop()
                display_manager_session.setup(restore=True)
                sys.exit(1)
        else:
            display_manager_session.stop()
            display_manager_session.setup(restore=True)
            sys.exit(1)

    if args.debug:
        os.environ["DOGTAIL_DEBUG"] = "true"

    if display_manager_name == "gdm":
        display_manager_session.set_accessibility_to(True)

    script = Script(script_command_list)

    if os.path.isfile('/tmp/headless_enable_fatal_criticals'):
        os.environ['G_DEBUG'] = 'fatal-criticals'
    if os.path.isfile('/tmp/headless_enable_fatal_warnings'):
        os.environ['G_DEBUG'] = 'fatal-warnings'

    pid = script.start()
    print("dogtail-run-headless-next: Started script with PID", pid)
    exit_code = script.wait()
    print("dogtail-run-headless-next: Script finished with return code", exit_code)

    if args.disable_a11y:
        display_manager_session.set_accessibility_to(False)

    if not args.dont_kill:
        display_manager_session.stop()
        display_manager_session.setup(restore=True)

    sys.exit(exit_code)


if __name__ == "__main__":
    main()