/mandos/trunk

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/trunk

« back to all changes in this revision

Viewing changes to mandos-ctl

  • Committer: Teddy Hogeborn
  • Date: 2015-05-23 20:18:34 UTC
  • mto: This revision was merged to the branch mainline in revision 756.
  • Revision ID: teddy@recompile.se-20150523201834-e89ex4ito93yni8x
mandos: Use multiprocessing module to run checkers.

For a long time, the Mandos server has occasionally logged the message
"ERROR: Child process vanished".  This was never a fatal error, but it
has been annoying and slightly worrying, since a definite cause was
not found.  One potential cause could be the "multiprocessing" and
"subprocess" modules conflicting w.r.t. SIGCHLD.  To avoid this,
change the running of checkers from using subprocess.Popen
asynchronously to instead first create a multiprocessing.Process()
(which is asynchronous) calling a function, and have that function
then call subprocess.call() (which is synchronous).  In this way, the
only thing using any asynchronous subprocesses is the multiprocessing
module.

This makes it necessary to change one small thing in the D-Bus API,
since the subprocesses.call() function does not expose the raw wait(2)
status value.

DBUS-API (CheckerCompleted): Change the second value provided by this
                             D-Bus signal from the raw wait(2) status
                             to the actual terminating signal number.
mandos (subprocess_call_pipe): New function to be called by
                               multiprocessing.Process (starting a
                               separate process).
(Client.last_checker signal): New attribute for signal which
                              terminated last checker.  Like
                              last_checker_status, only not accessible
                              via D-Bus.
(Client.checker_callback): Take new "connection" argument and use it
                           to get returncode; set last_checker_signal.
                           Return False so gobject does not call this
                           callback again.
(Client.start_checker): Start checker using a multiprocessing.Process
                        instead of a subprocess.Popen.
(ClientDBus.checker_callback): Take new "connection" argument.        Call
                               Client.checker_callback early to have
                               it set last_checker_status and
                               last_checker_signal; use those.  Change
                               second value provided to D-Bus signal
                               CheckerCompleted to use
                               last_checker_signal if checker was
                               terminated by signal.
mandos-monitor: Update to reflect DBus API change.
(MandosClientWidget.checker_completed): Take "signal" instead of
                                        "condition" argument.  Use it
                                        accordingly.  Remove dead code
                                        (os.WCOREDUMP case).

Show diffs side-by-side

added added

removed removed

Lines of Context:
3
3
4
4
# Mandos Monitor - Control and monitor the Mandos server
5
5
6
 
# Copyright © 2008-2016 Teddy Hogeborn
7
 
# Copyright © 2008-2016 Björn Påhlsson
 
6
# Copyright © 2008-2015 Teddy Hogeborn
 
7
# Copyright © 2008-2015 Björn Påhlsson
8
8
9
9
# This program is free software: you can redistribute it and/or modify
10
10
# it under the terms of the GNU General Public License as published by
39
39
import os
40
40
import collections
41
41
import doctest
42
 
import json
43
42
 
44
43
import dbus
45
44
 
65
64
    "ApprovalDelay": "Approval Delay",
66
65
    "ApprovalDuration": "Approval Duration",
67
66
    "Checker": "Checker",
68
 
    "ExtendedTimeout": "Extended Timeout",
69
 
    "Expires": "Expires",
70
 
    "LastCheckerStatus": "Last Checker Status",
 
67
    "ExtendedTimeout": "Extended Timeout"
71
68
}
72
69
defaultkeywords = ("Name", "Enabled", "Timeout", "LastCheckedOK")
73
70
domain = "se.recompile"
75
72
server_path = "/"
76
73
server_interface = domain + ".Mandos"
77
74
client_interface = domain + ".Mandos.Client"
78
 
version = "1.7.10"
79
 
 
80
 
 
81
 
try:
82
 
    dbus.OBJECT_MANAGER_IFACE
83
 
except AttributeError:
84
 
    dbus.OBJECT_MANAGER_IFACE = "org.freedesktop.DBus.ObjectManager"
 
75
version = "1.6.9"
 
76
 
85
77
 
86
78
def milliseconds_to_string(ms):
87
79
    td = datetime.timedelta(0, 0, 0, ms)
119
111
    # avoid excessive use of external libraries.
120
112
    
121
113
    # New type for defining tokens, syntax, and semantics all-in-one
122
 
    Token = collections.namedtuple("Token", (
123
 
        "regexp",  # To match token; if "value" is not None, must have
124
 
                   # a "group" containing digits
125
 
        "value",   # datetime.timedelta or None
126
 
        "followers"))           # Tokens valid after this token
 
114
    Token = collections.namedtuple("Token",
 
115
                                   ("regexp", # To match token; if
 
116
                                              # "value" is not None,
 
117
                                              # must have a "group"
 
118
                                              # containing digits
 
119
                                    "value",  # datetime.timedelta or
 
120
                                              # None
 
121
                                    "followers")) # Tokens valid after
 
122
                                                  # this token
127
123
    # RFC 3339 "duration" tokens, syntax, and semantics; taken from
128
124
    # the "duration" ABNF definition in RFC 3339, Appendix A.
129
125
    token_end = Token(re.compile(r"$"), None, frozenset())
182
178
                break
183
179
        else:
184
180
            # No currently valid tokens were found
185
 
            raise ValueError("Invalid RFC 3339 duration: {!r}"
186
 
                             .format(duration))
 
181
            raise ValueError("Invalid RFC 3339 duration")
187
182
    # End token found
188
183
    return value
189
184
 
191
186
def string_to_delta(interval):
192
187
    """Parse a string and return a datetime.timedelta
193
188
    
194
 
    >>> string_to_delta('7d')
 
189
    >>> string_to_delta("7d")
195
190
    datetime.timedelta(7)
196
 
    >>> string_to_delta('60s')
 
191
    >>> string_to_delta("60s")
197
192
    datetime.timedelta(0, 60)
198
 
    >>> string_to_delta('60m')
 
193
    >>> string_to_delta("60m")
199
194
    datetime.timedelta(0, 3600)
200
 
    >>> string_to_delta('24h')
 
195
    >>> string_to_delta("24h")
201
196
    datetime.timedelta(1)
202
 
    >>> string_to_delta('1w')
 
197
    >>> string_to_delta("1w")
203
198
    datetime.timedelta(7)
204
 
    >>> string_to_delta('5m 30s')
 
199
    >>> string_to_delta("5m 30s")
205
200
    datetime.timedelta(0, 330)
206
201
    """
207
202
    
283
278
                        help="Select all clients")
284
279
    parser.add_argument("-v", "--verbose", action="store_true",
285
280
                        help="Print all fields")
286
 
    parser.add_argument("-j", "--dump-json", action="store_true",
287
 
                        help="Dump client data in JSON format")
288
281
    parser.add_argument("-e", "--enable", action="store_true",
289
282
                        help="Enable client")
290
283
    parser.add_argument("-d", "--disable", action="store_true",
333
326
    if has_actions(options) and not (options.client or options.all):
334
327
        parser.error("Options require clients names or --all.")
335
328
    if options.verbose and has_actions(options):
336
 
        parser.error("--verbose can only be used alone.")
337
 
    if options.dump_json and (options.verbose or has_actions(options)):
338
 
        parser.error("--dump-json can only be used alone.")
 
329
        parser.error("--verbose can only be used alone or with"
 
330
                     " --all.")
339
331
    if options.all and not has_actions(options):
340
332
        parser.error("--all requires an action.")
341
 
    
 
333
 
342
334
    if options.check:
343
335
        fail_count, test_count = doctest.testmod()
344
336
        sys.exit(os.EX_OK if fail_count == 0 else 1)
352
344
    
353
345
    mandos_serv = dbus.Interface(mandos_dbus_objc,
354
346
                                 dbus_interface = server_interface)
355
 
    mandos_serv_object_manager = dbus.Interface(
356
 
        mandos_dbus_objc, dbus_interface = dbus.OBJECT_MANAGER_IFACE)
357
347
    
358
348
    #block stderr since dbus library prints to stderr
359
349
    null = os.open(os.path.devnull, os.O_RDWR)
362
352
    os.close(null)
363
353
    try:
364
354
        try:
365
 
            mandos_clients = { path: ifs_and_props[client_interface]
366
 
                               for path, ifs_and_props in
367
 
                               mandos_serv_object_manager
368
 
                               .GetManagedObjects().items()
369
 
                               if client_interface in ifs_and_props }
 
355
            mandos_clients = mandos_serv.GetAllClientsWithProperties()
370
356
        finally:
371
357
            #restore stderr
372
358
            os.dup2(stderrcopy, sys.stderr.fileno())
373
359
            os.close(stderrcopy)
374
 
    except dbus.exceptions.DBusException as e:
375
 
        print("Access denied: Accessing mandos server through D-Bus: {}"
376
 
              .format(e), file=sys.stderr)
 
360
    except dbus.exceptions.DBusException:
 
361
        print("Access denied: Accessing mandos server through dbus.",
 
362
              file=sys.stderr)
377
363
        sys.exit(1)
378
364
    
379
365
    # Compile dict of (clients: properties) to process
395
381
                sys.exit(1)
396
382
    
397
383
    if not has_actions(options) and clients:
398
 
        if options.verbose or options.dump_json:
 
384
        if options.verbose:
399
385
            keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK",
400
386
                        "Created", "Interval", "Host", "Fingerprint",
401
387
                        "CheckerRunning", "LastEnabled",
402
388
                        "ApprovalPending", "ApprovedByDefault",
403
389
                        "LastApprovalRequest", "ApprovalDelay",
404
390
                        "ApprovalDuration", "Checker",
405
 
                        "ExtendedTimeout", "Expires",
406
 
                        "LastCheckerStatus")
 
391
                        "ExtendedTimeout")
407
392
        else:
408
393
            keywords = defaultkeywords
409
394
        
410
 
        if options.dump_json:
411
 
            json.dump({client["Name"]: {key:
412
 
                                        bool(client[key])
413
 
                                        if isinstance(client[key],
414
 
                                                      dbus.Boolean)
415
 
                                        else client[key]
416
 
                                        for key in keywords }
417
 
                       for client in clients.values() },
418
 
                      fp = sys.stdout, indent = 4,
419
 
                      separators = (',', ': '))
420
 
            print()
421
 
        else:
422
 
            print_clients(clients.values(), keywords)
 
395
        print_clients(clients.values(), keywords)
423
396
    else:
424
397
        # Process each client in the list by all selected options
425
398
        for client in clients: