/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: Björn Påhlsson
  • Date: 2010-09-12 18:12:11 UTC
  • mto: (237.4.3 mandos-release)
  • mto: This revision was merged to the branch mainline in revision 428.
  • Revision ID: belorn@fukt.bsnet.se-20100912181211-wvkt0sk37zhx7tws
mandos-client: Added never ending loop for --connect
mandos-ctl: Better option parsing.

Show diffs side-by-side

added added

removed removed

Lines of Context:
40
40
urwid.curses_display.curses.A_UNDERLINE |= (
41
41
    urwid.curses_display.curses.A_BLINK)
42
42
 
 
43
def isoformat_to_datetime(iso):
 
44
    "Parse an ISO 8601 date string to a datetime.datetime()"
 
45
    if not iso:
 
46
        return None
 
47
    d, t = iso.split(u"T", 1)
 
48
    year, month, day = d.split(u"-", 2)
 
49
    hour, minute, second = t.split(u":", 2)
 
50
    second, fraction = divmod(float(second), 1)
 
51
    return datetime.datetime(int(year),
 
52
                             int(month),
 
53
                             int(day),
 
54
                             int(hour),
 
55
                             int(minute),
 
56
                             int(second),           # Whole seconds
 
57
                             int(fraction*1000000)) # Microseconds
 
58
 
43
59
class MandosClientPropertyCache(object):
44
60
    """This wraps a Mandos Client D-Bus proxy object, caches the
45
61
    properties and calls a hook function when any of them are
57
73
        self.properties.update(
58
74
            self.proxy.GetAll(client_interface,
59
75
                              dbus_interface = dbus.PROPERTIES_IFACE))
60
 
        super(MandosClientPropertyCache, self).__init__(
61
 
            proxy_object=proxy_object, *args, **kwargs)
 
76
 
 
77
        #XXX This break good super behaviour!
 
78
#        super(MandosClientPropertyCache, self).__init__(
 
79
#            *args, **kwargs)
62
80
    
63
81
    def property_changed(self, property=None, value=None):
64
82
        """This is called whenever we get a PropertyChanged signal
83
101
        # Logger
84
102
        self.logger = logger
85
103
        
 
104
        self._update_timer_callback_tag = None
 
105
        self.last_checker_failed = False
 
106
        
86
107
        # The widget shown normally
87
108
        self._text_widget = urwid.Text(u"")
88
109
        # The widget shown when we have focus
112
133
                                     self.rejected,
113
134
                                     client_interface,
114
135
                                     byte_arrays=True)
 
136
        last_checked_ok = isoformat_to_datetime(self.properties
 
137
                                                ["last_checked_ok"])
 
138
        if last_checked_ok is None:
 
139
            self.last_checker_failed = True
 
140
        else:
 
141
            self.last_checker_failed = ((datetime.datetime.utcnow()
 
142
                                         - last_checked_ok)
 
143
                                        > datetime.timedelta
 
144
                                        (milliseconds=
 
145
                                         self.properties["interval"]))
 
146
        if self.last_checker_failed:
 
147
            self._update_timer_callback_tag = (gobject.timeout_add
 
148
                                               (1000,
 
149
                                                self.update_timer))
115
150
    
116
151
    def checker_completed(self, exitstatus, condition, command):
117
152
        if exitstatus == 0:
118
 
            #self.logger(u'Checker for client %s (command "%s")'
119
 
            #            u' was successful'
120
 
            #            % (self.properties[u"name"], command))
 
153
            if self.last_checker_failed:
 
154
                self.last_checker_failed = False
 
155
                gobject.source_remove(self._update_timer_callback_tag)
 
156
                self._update_timer_callback_tag = None
 
157
            self.logger(u'Checker for client %s (command "%s")'
 
158
                        u' was successful'
 
159
                        % (self.properties[u"name"], command))
 
160
            self.update()
121
161
            return
 
162
        # Checker failed
 
163
        if not self.last_checker_failed:
 
164
            self.last_checker_failed = True
 
165
            self._update_timer_callback_tag = (gobject.timeout_add
 
166
                                               (1000,
 
167
                                                self.update_timer))
122
168
        if os.WIFEXITED(condition):
123
169
            self.logger(u'Checker for client %s (command "%s")'
124
170
                        u' failed with exit code %s'
125
171
                        % (self.properties[u"name"], command,
126
172
                           os.WEXITSTATUS(condition)))
127
 
            return
128
 
        if os.WIFSIGNALED(condition):
 
173
        elif os.WIFSIGNALED(condition):
129
174
            self.logger(u'Checker for client %s (command "%s")'
130
175
                        u' was killed by signal %s'
131
176
                        % (self.properties[u"name"], command,
132
177
                           os.WTERMSIG(condition)))
133
 
            return
134
 
        if os.WCOREDUMP(condition):
 
178
        elif os.WCOREDUMP(condition):
135
179
            self.logger(u'Checker for client %s (command "%s")'
136
180
                        u' dumped core'
137
181
                        % (self.properties[u"name"], command))
138
 
        self.logger(u'Checker for client %s completed mysteriously')
 
182
        else:
 
183
            self.logger(u'Checker for client %s completed mysteriously')
 
184
        self.update()
139
185
    
140
186
    def checker_started(self, command):
141
187
        #self.logger(u'Client %s started checker "%s"'
143
189
        pass
144
190
    
145
191
    def got_secret(self):
 
192
        self.last_checker_failed = False
146
193
        self.logger(u'Client %s received its secret'
147
194
                    % self.properties[u"name"])
148
195
    
184
231
                          u"bold-underline-blink":
185
232
                              u"bold-underline-blink-standout",
186
233
                          }
187
 
        
 
234
 
188
235
        # Rebuild focus and non-focus widgets using current properties
189
 
        self._text = (u'%(name)s: %(enabled)s'
190
 
                      % { u"name": self.properties[u"name"],
191
 
                          u"enabled":
192
 
                              (u"enabled"
193
 
                               if self.properties[u"enabled"]
194
 
                               else u"DISABLED")})
 
236
 
 
237
        # Base part of a client. Name!
 
238
        base = (u'%(name)s: '
 
239
                      % {u"name": self.properties[u"name"]})
 
240
        if not self.properties[u"enabled"]:
 
241
            message = u"DISABLED"
 
242
        elif self.properties[u"approved_pending"]:
 
243
            if self.properties[u"approved_by_default"]:
 
244
                message = u"Connection established to client. (d)eny?"
 
245
            else:
 
246
                message = u"Seeks approval to send secret. (a)pprove?"
 
247
        elif self.last_checker_failed:
 
248
            timeout = datetime.timedelta(milliseconds
 
249
                                         = self.properties[u"timeout"])
 
250
            last_ok = isoformat_to_datetime(
 
251
                max((self.properties["last_checked_ok"]
 
252
                     or self.properties["created"]),
 
253
                    self.properties[u"last_enabled"]))
 
254
            timer = timeout - (datetime.datetime.utcnow() - last_ok)
 
255
            message = (u'A checker has failed! Time until client gets diabled: %s'
 
256
                           % unicode(timer).rsplit(".", 1)[0])
 
257
        else:
 
258
            message = u"enabled"
 
259
        self._text = "%s%s" % (base, message)
 
260
            
195
261
        if not urwid.supports_unicode():
196
262
            self._text = self._text.encode("ascii", "replace")
197
263
        textlist = [(u"normal", self._text)]
208
274
        if self.update_hook is not None:
209
275
            self.update_hook()
210
276
    
 
277
    def update_timer(self):
 
278
        "called by gobject"
 
279
        self.update()
 
280
        return True             # Keep calling this
 
281
    
211
282
    def delete(self):
 
283
        if self._update_timer_callback_tag is not None:
 
284
            gobject.source_remove(self._update_timer_callback_tag)
 
285
            self._update_timer_callback_tag = None
212
286
        if self.delete_hook is not None:
213
287
            self.delete_hook(self)
214
288
    
221
295
    def keypress(self, (maxcol,), key):
222
296
        """Handle keys.
223
297
        This overrides the method from urwid.FlowWidget"""
224
 
        if key == u"e" or key == u"+":
225
 
            self.proxy.Enable()
226
 
        elif key == u"d" or key == u"-":
227
 
            self.proxy.Disable()
 
298
        if key == u"+":
 
299
            self.proxy.Enable(dbus_interface = client_interface)
 
300
        elif key == u"-":
 
301
            self.proxy.Disable(dbus_interface = client_interface)
 
302
        elif key == u"a":
 
303
            self.proxy.Approve(dbus.Boolean(True, variant_level=1),
 
304
                               dbus_interface = client_interface)
 
305
        elif key == u"d":
 
306
            self.proxy.Approve(dbus.Boolean(False, variant_level=1),
 
307
                                  dbus_interface = client_interface)
228
308
        elif key == u"r" or key == u"_" or key == u"ctrl k":
229
309
            self.server_proxy_object.RemoveClient(self.proxy
230
310
                                                  .object_path)
231
311
        elif key == u"s":
232
 
            self.proxy.StartChecker()
 
312
            self.proxy.StartChecker(dbus_interface = client_interface)
233
313
        elif key == u"S":
234
 
            self.proxy.StopChecker()
 
314
            self.proxy.StopChecker(dbus_interface = client_interface)
235
315
        elif key == u"C":
236
 
            self.proxy.CheckedOK()
 
316
            self.proxy.CheckedOK(dbus_interface = client_interface)
237
317
        # xxx
238
318
#         elif key == u"p" or key == "=":
239
319
#             self.proxy.pause()
241
321
#             self.proxy.unpause()
242
322
#         elif key == u"RET":
243
323
#             self.open()
244
 
        elif key == u"+":
245
 
            self.proxy.Approve(True)
246
 
        elif key == u"-":
247
 
            self.proxy.Approve(False)
 
324
#        elif key == u"+":
 
325
#            self.proxy.Approve(True)
 
326
#        elif key == u"-":
 
327
#            self.proxy.Approve(False)
248
328
        else:
249
329
            return key
250
330
    
542
622
                self.log_message_raw((u"bold",
543
623
                                      u"  "
544
624
                                      .join((u"Clients:",
545
 
                                             u"e: Enable",
546
 
                                             u"d: Disable",
 
625
                                             u"+: Enable",
 
626
                                             u"-: Disable",
547
627
                                             u"r: Remove",
548
628
                                             u"s: Start new checker",
549
629
                                             u"S: Stop checker",
550
 
                                             u"C: Checker OK"))))
 
630
                                             u"C: Checker OK",
 
631
                                             u"a: Approve",
 
632
                                             u"d: Deny"))))
551
633
                self.refresh()
552
634
            elif key == u"tab":
553
635
                if self.topwidget.get_focus() is self.logbox:
581
663
ui = UserInterface()
582
664
try:
583
665
    ui.run()
 
666
except KeyboardInterrupt:
 
667
    ui.screen.stop()
584
668
except Exception, e:
585
669
    ui.log_message(unicode(e))
586
670
    ui.screen.stop()