/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-monitor

  • Committer: Teddy Hogeborn
  • Date: 2014-08-09 13:18:46 UTC
  • Revision ID: teddy@recompile.se-20140809131846-2emd272mf9c9wihe
mandos: Replace unicode() with str().

This is in preparation for the coming Python 3 conversion.

* mandos: Replace "str" with "unicode".  All callers changed.

Show diffs side-by-side

added added

removed removed

Lines of Context:
48
48
 
49
49
import locale
50
50
 
51
 
if sys.version_info[0] == 2:
 
51
if sys.version_info.major == 2:
52
52
    str = unicode
53
53
 
54
54
locale.setlocale(locale.LC_ALL, '')
60
60
domain = 'se.recompile'
61
61
server_interface = domain + '.Mandos'
62
62
client_interface = domain + '.Mandos.Client'
63
 
version = "1.6.4"
 
63
version = "1.6.8"
64
64
 
65
65
def isoformat_to_datetime(iso):
66
66
    "Parse an ISO 8601 date string to a datetime.datetime()"
161
161
                                         self.rejected,
162
162
                                         client_interface,
163
163
                                         byte_arrays=True))
164
 
        #self.logger('Created client {0}'
165
 
        #            .format(self.properties["Name"]))
 
164
        self.logger('Created client {}'
 
165
                    .format(self.properties["Name"]), level=0)
166
166
    
167
167
    def using_timer(self, flag):
168
168
        """Call this method with True or False when timer should be
179
179
    
180
180
    def checker_completed(self, exitstatus, condition, command):
181
181
        if exitstatus == 0:
 
182
            self.logger('Checker for client {} (command "{}")'
 
183
                        ' succeeded'.format(self.properties["Name"],
 
184
                                            command), level=0)
182
185
            self.update()
183
186
            return
184
187
        # Checker failed
185
188
        if os.WIFEXITED(condition):
186
 
            self.logger('Checker for client {0} (command "{1}")'
187
 
                        ' failed with exit code {2}'
 
189
            self.logger('Checker for client {} (command "{}") failed'
 
190
                        ' with exit code {}'
188
191
                        .format(self.properties["Name"], command,
189
192
                                os.WEXITSTATUS(condition)))
190
193
        elif os.WIFSIGNALED(condition):
191
 
            self.logger('Checker for client {0} (command "{1}") was'
192
 
                        ' killed by signal {2}'
 
194
            self.logger('Checker for client {} (command "{}") was'
 
195
                        ' killed by signal {}'
193
196
                        .format(self.properties["Name"], command,
194
197
                                os.WTERMSIG(condition)))
195
198
        elif os.WCOREDUMP(condition):
196
 
            self.logger('Checker for client {0} (command "{1}")'
197
 
                        ' dumped core'
198
 
                        .format(self.properties["Name"], command))
 
199
            self.logger('Checker for client {} (command "{}") dumped'
 
200
                        ' core'.format(self.properties["Name"],
 
201
                                       command))
199
202
        else:
200
 
            self.logger('Checker for client {0} completed'
 
203
            self.logger('Checker for client {} completed'
201
204
                        ' mysteriously'
202
205
                        .format(self.properties["Name"]))
203
206
        self.update()
204
207
    
205
208
    def checker_started(self, command):
206
 
        """Server signals that a checker started. This could be useful
207
 
           to log in the future. """
208
 
        #self.logger('Client {0} started checker "{1}"'
209
 
        #            .format(self.properties["Name"],
210
 
        #                    str(command)))
211
 
        pass
 
209
        """Server signals that a checker started."""
 
210
        self.logger('Client {} started checker "{}"'
 
211
                    .format(self.properties["Name"],
 
212
                            command), level=0)
212
213
    
213
214
    def got_secret(self):
214
 
        self.logger('Client {0} received its secret'
 
215
        self.logger('Client {} received its secret'
215
216
                    .format(self.properties["Name"]))
216
217
    
217
218
    def need_approval(self, timeout, default):
218
219
        if not default:
219
 
            message = 'Client {0} needs approval within {1} seconds'
 
220
            message = 'Client {} needs approval within {} seconds'
220
221
        else:
221
 
            message = 'Client {0} will get its secret in {1} seconds'
 
222
            message = 'Client {} will get its secret in {} seconds'
222
223
        self.logger(message.format(self.properties["Name"],
223
224
                                   timeout/1000))
224
225
    
225
226
    def rejected(self, reason):
226
 
        self.logger('Client {0} was rejected; reason: {1}'
 
227
        self.logger('Client {} was rejected; reason: {}'
227
228
                    .format(self.properties["Name"], reason))
228
229
    
229
230
    def selectable(self):
273
274
            else:
274
275
                timer = datetime.timedelta()
275
276
            if self.properties["ApprovedByDefault"]:
276
 
                message = "Approval in {0}. (d)eny?"
 
277
                message = "Approval in {}. (d)eny?"
277
278
            else:
278
 
                message = "Denial in {0}. (a)pprove?"
 
279
                message = "Denial in {}. (a)pprove?"
279
280
            message = message.format(str(timer).rsplit(".", 1)[0])
280
281
            self.using_timer(True)
281
282
        elif self.properties["LastCheckerStatus"] != 0:
289
290
                timer = max(expires - datetime.datetime.utcnow(),
290
291
                            datetime.timedelta())
291
292
            message = ('A checker has failed! Time until client'
292
 
                       ' gets disabled: {0}'
 
293
                       ' gets disabled: {}'
293
294
                       .format(str(timer).rsplit(".", 1)[0]))
294
295
            self.using_timer(True)
295
296
        else:
296
297
            message = "enabled"
297
298
            self.using_timer(False)
298
 
        self._text = "{0}{1}".format(base, message)
 
299
        self._text = "{}{}".format(base, message)
299
300
        
300
301
        if not urwid.supports_unicode():
301
302
            self._text = self._text.encode("ascii", "replace")
403
404
    """This is the entire user interface - the whole screen
404
405
    with boxes, lists of client widgets, etc.
405
406
    """
406
 
    def __init__(self, max_log_length=1000):
 
407
    def __init__(self, max_log_length=1000, log_level=1):
407
408
        DBusGMainLoop(set_as_default=True)
408
409
        
409
410
        self.screen = urwid.curses_display.Screen()
447
448
        self.log = []
448
449
        self.max_log_length = max_log_length
449
450
        
 
451
        self.log_level = log_level
 
452
        
450
453
        # We keep a reference to the log widget so we can remove it
451
454
        # from the ListWalker without it getting destroyed
452
455
        self.logbox = ConstrainedListBox(self.log)
466
469
        self.main_loop = gobject.MainLoop()
467
470
    
468
471
    def client_not_found(self, fingerprint, address):
469
 
        self.log_message("Client with address {0} and fingerprint"
470
 
                         " {1} could not be found"
 
472
        self.log_message("Client with address {} and fingerprint {}"
 
473
                         " could not be found"
471
474
                         .format(address, fingerprint))
472
475
    
473
476
    def rebuild(self):
486
489
            self.uilist.append(self.logbox)
487
490
        self.topwidget = urwid.Pile(self.uilist)
488
491
    
489
 
    def log_message(self, message):
 
492
    def log_message(self, message, level=1):
490
493
        """Log message formatted with timestamp"""
 
494
        if level < self.log_level:
 
495
            return
491
496
        timestamp = datetime.datetime.now().isoformat()
492
 
        self.log_message_raw(timestamp + ": " + message)
 
497
        self.log_message_raw("{}: {}".format(timestamp, message),
 
498
                             level=level)
493
499
    
494
 
    def log_message_raw(self, markup):
 
500
    def log_message_raw(self, markup, level=1):
495
501
        """Add a log message to the log buffer."""
 
502
        if level < self.log_level:
 
503
            return
496
504
        self.log.append(urwid.Text(markup, wrap=self.log_wrap))
497
505
        if (self.max_log_length
498
506
            and len(self.log) > self.max_log_length):
505
513
        """Toggle visibility of the log buffer."""
506
514
        self.log_visible = not self.log_visible
507
515
        self.rebuild()
508
 
        #self.log_message("Log visibility changed to: "
509
 
        #                 + str(self.log_visible))
 
516
        self.log_message("Log visibility changed to: {}"
 
517
                         .format(self.log_visible), level=0)
510
518
    
511
519
    def change_log_display(self):
512
520
        """Change type of log display.
517
525
            self.log_wrap = "clip"
518
526
        for textwidget in self.log:
519
527
            textwidget.set_wrap_mode(self.log_wrap)
520
 
        #self.log_message("Wrap mode: " + self.log_wrap)
 
528
        self.log_message("Wrap mode: {}".format(self.log_wrap),
 
529
                         level=0)
521
530
    
522
531
    def find_and_remove_client(self, path, name):
523
532
        """Find a client by its object path and remove it.
528
537
            client = self.clients_dict[path]
529
538
        except KeyError:
530
539
            # not found?
531
 
            self.log_message("Unknown client {0!r} ({1!r}) removed"
 
540
            self.log_message("Unknown client {!r} ({!r}) removed"
532
541
                             .format(name, path))
533
542
            return
534
543
        client.delete()
652
661
            elif key == "window resize":
653
662
                self.size = self.screen.get_cols_rows()
654
663
                self.refresh()
655
 
            elif key == "\f":  # Ctrl-L
 
664
            elif key == "ctrl l":
 
665
                self.screen.clear()
656
666
                self.refresh()
657
667
            elif key == "l" or key == "D":
658
668
                self.toggle_log_display()
670
680
                                            "?: Help",
671
681
                                            "l: Log window toggle",
672
682
                                            "TAB: Switch window",
673
 
                                            "w: Wrap (log)"))))
 
683
                                            "w: Wrap (log lines)",
 
684
                                            "v: Toggle verbose log",
 
685
                                            ))))
674
686
                self.log_message_raw(("bold",
675
687
                                      "  "
676
688
                                      .join(("Clients:",
689
701
                else:
690
702
                    self.topwidget.set_focus(self.logbox)
691
703
                self.refresh()
 
704
            elif key == "v":
 
705
                if self.log_level == 0:
 
706
                    self.log_level = 1
 
707
                    self.log_message("Verbose mode: Off")
 
708
                else:
 
709
                    self.log_level = 0
 
710
                    self.log_message("Verbose mode: On")
692
711
            #elif (key == "end" or key == "meta >" or key == "G"
693
712
            #      or key == ">"):
694
713
            #    pass            # xxx end-of-buffer