/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-07 20:22:16 UTC
  • mto: (237.4.3 mandos-release)
  • mto: This revision was merged to the branch mainline in revision 421.
  • Revision ID: belorn@fukt.bsnet.se-20100907202216-vypcn3nsd02mqz4s
mandos-monitor: removed milisecondsseconds from countdown.

Show diffs side-by-side

added added

removed removed

Lines of Context:
23
23
 
24
24
locale.setlocale(locale.LC_ALL, u'')
25
25
 
 
26
import logging
 
27
logging.getLogger('dbus.proxies').setLevel(logging.CRITICAL)
 
28
 
26
29
# Some useful constants
27
30
domain = 'se.bsnet.fukt'
28
31
server_interface = domain + '.Mandos'
29
32
client_interface = domain + '.Mandos.Client'
30
 
version = "1.0.14"
 
33
version = "1.0.15"
31
34
 
32
35
# Always run in monochrome mode
33
36
urwid.curses_display.curses.has_colors = lambda : False
37
40
urwid.curses_display.curses.A_UNDERLINE |= (
38
41
    urwid.curses_display.curses.A_BLINK)
39
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
 
40
59
class MandosClientPropertyCache(object):
41
60
    """This wraps a Mandos Client D-Bus proxy object, caches the
42
61
    properties and calls a hook function when any of them are
50
69
                                     self.property_changed,
51
70
                                     client_interface,
52
71
                                     byte_arrays=True)
53
 
 
 
72
        
54
73
        self.properties.update(
55
74
            self.proxy.GetAll(client_interface,
56
75
                              dbus_interface = dbus.PROPERTIES_IFACE))
57
 
        super(MandosClientPropertyCache, self).__init__(
58
 
            proxy_object=proxy_object, *args, **kwargs)
 
76
 
 
77
        #XXX This break good super behaviour!
 
78
#        super(MandosClientPropertyCache, self).__init__(
 
79
#            *args, **kwargs)
59
80
    
60
81
    def property_changed(self, property=None, value=None):
61
82
        """This is called whenever we get a PropertyChanged signal
80
101
        # Logger
81
102
        self.logger = logger
82
103
        
 
104
        self._update_timer_callback_tag = None
 
105
        self.last_checker_failed = False
 
106
        
83
107
        # The widget shown normally
84
108
        self._text_widget = urwid.Text(u"")
85
109
        # The widget shown when we have focus
101
125
                                     self.got_secret,
102
126
                                     client_interface,
103
127
                                     byte_arrays=True)
 
128
        self.proxy.connect_to_signal(u"NeedApproval",
 
129
                                     self.need_approval,
 
130
                                     client_interface,
 
131
                                     byte_arrays=True)
104
132
        self.proxy.connect_to_signal(u"Rejected",
105
133
                                     self.rejected,
106
134
                                     client_interface,
107
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))
108
150
    
109
151
    def checker_completed(self, exitstatus, condition, command):
110
152
        if exitstatus == 0:
 
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
111
157
            self.logger(u'Checker for client %s (command "%s")'
112
158
                        u' was successful'
113
159
                        % (self.properties[u"name"], command))
 
160
            self.update()
114
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))
115
168
        if os.WIFEXITED(condition):
116
169
            self.logger(u'Checker for client %s (command "%s")'
117
170
                        u' failed with exit code %s'
118
171
                        % (self.properties[u"name"], command,
119
172
                           os.WEXITSTATUS(condition)))
120
 
            return
121
 
        if os.WIFSIGNALED(condition):
 
173
        elif os.WIFSIGNALED(condition):
122
174
            self.logger(u'Checker for client %s (command "%s")'
123
175
                        u' was killed by signal %s'
124
176
                        % (self.properties[u"name"], command,
125
177
                           os.WTERMSIG(condition)))
126
 
            return
127
 
        if os.WCOREDUMP(condition):
 
178
        elif os.WCOREDUMP(condition):
128
179
            self.logger(u'Checker for client %s (command "%s")'
129
180
                        u' dumped core'
130
181
                        % (self.properties[u"name"], command))
131
 
        self.logger(u'Checker for client %s completed mysteriously')
 
182
        else:
 
183
            self.logger(u'Checker for client %s completed mysteriously')
 
184
        self.update()
132
185
    
133
186
    def checker_started(self, command):
134
 
        self.logger(u'Client %s started checker "%s"'
135
 
                    % (self.properties[u"name"], unicode(command)))
 
187
        #self.logger(u'Client %s started checker "%s"'
 
188
        #            % (self.properties[u"name"], unicode(command)))
 
189
        pass
136
190
    
137
191
    def got_secret(self):
138
192
        self.logger(u'Client %s received its secret'
139
193
                    % self.properties[u"name"])
140
194
    
141
 
    def rejected(self):
142
 
        self.logger(u'Client %s was rejected'
143
 
                    % self.properties[u"name"])
 
195
    def need_approval(self, timeout, default):
 
196
        if not default:
 
197
            message = u'Client %s needs approval within %s seconds'
 
198
        else:
 
199
            message = u'Client %s will get its secret in %s seconds'
 
200
        self.logger(message
 
201
                    % (self.properties[u"name"], timeout/1000))
 
202
    
 
203
    def rejected(self, reason):
 
204
        self.logger(u'Client %s was rejected; reason: %s'
 
205
                    % (self.properties[u"name"], reason))
144
206
    
145
207
    def selectable(self):
146
208
        """Make this a "selectable" widget.
168
230
                          u"bold-underline-blink":
169
231
                              u"bold-underline-blink-standout",
170
232
                          }
171
 
        
 
233
 
172
234
        # Rebuild focus and non-focus widgets using current properties
173
 
        self._text = (u'%(name)s: %(enabled)s'
174
 
                      % { u"name": self.properties[u"name"],
175
 
                          u"enabled":
176
 
                              (u"enabled"
177
 
                               if self.properties[u"enabled"]
178
 
                               else u"DISABLED")})
 
235
 
 
236
        # Base part of a client. Name!
 
237
        base = (u'%(name)s: '
 
238
                      % {u"name": self.properties[u"name"]})
 
239
        if not self.properties[u"enabled"]:
 
240
            message = u"DISABLED"
 
241
        elif self.last_checker_failed:
 
242
            timeout = datetime.timedelta(milliseconds
 
243
                                         = self.properties[u"timeout"])
 
244
            last_ok = isoformat_to_datetime(
 
245
                max((self.properties["last_checked_ok"]
 
246
                     or self.properties["created"]),
 
247
                    self.properties[u"last_enabled"]))
 
248
            timer = timeout - (datetime.datetime.utcnow() - last_ok)
 
249
            message = (u'A checker has failed! Time until client gets diabled: %s'
 
250
                           % unicode(timer).rsplit(".", 1)[0])
 
251
        elif self.properties[u"approved_pending"]:
 
252
            if self.properties[u"approved_by_default"]:
 
253
                message = u"Connection established to client. (d)eny?"
 
254
            else:
 
255
                message = u"Seeks approval to send secret. (a)pprove?"
 
256
        else:
 
257
            message = u"enabled"
 
258
        self._text = "%s%s" % (base, message)
 
259
            
179
260
        if not urwid.supports_unicode():
180
261
            self._text = self._text.encode("ascii", "replace")
181
262
        textlist = [(u"normal", self._text)]
192
273
        if self.update_hook is not None:
193
274
            self.update_hook()
194
275
    
 
276
    def update_timer(self):
 
277
        "called by gobject"
 
278
        self.update()
 
279
        return True             # Keep calling this
 
280
    
195
281
    def delete(self):
 
282
        if self._update_timer_callback_tag is not None:
 
283
            gobject.source_remove(self._update_timer_callback_tag)
 
284
            self._update_timer_callback_tag = None
196
285
        if self.delete_hook is not None:
197
286
            self.delete_hook(self)
198
287
    
205
294
    def keypress(self, (maxcol,), key):
206
295
        """Handle keys.
207
296
        This overrides the method from urwid.FlowWidget"""
208
 
        if key == u"e" or key == u"+":
209
 
            self.proxy.Enable()
210
 
        elif key == u"d" or key == u"-":
211
 
            self.proxy.Disable()
 
297
        if key == u"+":
 
298
            self.proxy.Enable(dbus_interface = client_interface)
 
299
        elif key == u"-":
 
300
            self.proxy.Disable(dbus_interface = client_interface)
 
301
        elif key == u"a":
 
302
            self.proxy.Approve(dbus.Boolean(True, variant_level=1),
 
303
                               dbus_interface = client_interface)
 
304
        elif key == u"d":
 
305
            self.proxy.Approve(dbus.Boolean(False, variant_level=1),
 
306
                                  dbus_interface = client_interface)
212
307
        elif key == u"r" or key == u"_" or key == u"ctrl k":
213
308
            self.server_proxy_object.RemoveClient(self.proxy
214
309
                                                  .object_path)
215
310
        elif key == u"s":
216
 
            self.proxy.StartChecker()
 
311
            self.proxy.StartChecker(dbus_interface = client_interface)
217
312
        elif key == u"S":
218
 
            self.proxy.StopChecker()
 
313
            self.proxy.StopChecker(dbus_interface = client_interface)
219
314
        elif key == u"C":
220
 
            self.proxy.CheckedOK()
 
315
            self.proxy.CheckedOK(dbus_interface = client_interface)
221
316
        # xxx
222
317
#         elif key == u"p" or key == "=":
223
318
#             self.proxy.pause()
225
320
#             self.proxy.unpause()
226
321
#         elif key == u"RET":
227
322
#             self.open()
 
323
#        elif key == u"+":
 
324
#            self.proxy.Approve(True)
 
325
#        elif key == u"-":
 
326
#            self.proxy.Approve(False)
228
327
        else:
229
328
            return key
230
329
    
522
621
                self.log_message_raw((u"bold",
523
622
                                      u"  "
524
623
                                      .join((u"Clients:",
525
 
                                             u"e: Enable",
526
 
                                             u"d: Disable",
 
624
                                             u"+: Enable",
 
625
                                             u"-: Disable",
527
626
                                             u"r: Remove",
528
627
                                             u"s: Start new checker",
529
628
                                             u"S: Stop checker",
530
 
                                             u"C: Checker OK"))))
 
629
                                             u"C: Checker OK",
 
630
                                             u"a: Approve",
 
631
                                             u"d: Deny"))))
531
632
                self.refresh()
532
633
            elif key == u"tab":
533
634
                if self.topwidget.get_focus() is self.logbox: