/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: 2010-09-05 20:19:02 UTC
  • mfrom: (416.1.2 mandos)
  • Revision ID: teddy@fukt.bsnet.se-20100905201902-ivwsc01ecaaqlqg4
* mandos (AvahiService.entry_group_state_changed): Better debug log
                                                   message.
  (AvahiService.server_state_changed): Added debug log message.

* mandos-monitor (isoformat_to_datetime): New function.
  (MandosClientWidget): Show a countdown to disabling if last checker
                        failed.

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
 
 
29
26
# Some useful constants
30
27
domain = 'se.bsnet.fukt'
31
28
server_interface = domain + '.Mandos'
32
29
client_interface = domain + '.Mandos.Client'
33
 
version = "1.0.15"
 
30
version = "1.0.14"
34
31
 
35
32
# Always run in monochrome mode
36
33
urwid.curses_display.curses.has_colors = lambda : False
40
37
urwid.curses_display.curses.A_UNDERLINE |= (
41
38
    urwid.curses_display.curses.A_BLINK)
42
39
 
 
40
def isoformat_to_datetime(iso):
 
41
    "Parse an ISO 8601 date string to a datetime.datetime()"
 
42
    if not iso:
 
43
        return None
 
44
    d, t = iso.split(u"T", 1)
 
45
    year, month, day = d.split(u"-", 2)
 
46
    hour, minute, second = t.split(u":", 2)
 
47
    second, fraction = divmod(float(second), 1)
 
48
    return datetime.datetime(int(year),
 
49
                             int(month),
 
50
                             int(day),
 
51
                             int(hour),
 
52
                             int(minute),
 
53
                             int(second),           # Whole seconds
 
54
                             int(fraction*1000000)) # Microseconds
 
55
 
43
56
class MandosClientPropertyCache(object):
44
57
    """This wraps a Mandos Client D-Bus proxy object, caches the
45
58
    properties and calls a hook function when any of them are
57
70
        self.properties.update(
58
71
            self.proxy.GetAll(client_interface,
59
72
                              dbus_interface = dbus.PROPERTIES_IFACE))
60
 
 
61
 
        #XXX This break good super behaviour!
62
 
#        super(MandosClientPropertyCache, self).__init__(
63
 
#            *args, **kwargs)
 
73
        super(MandosClientPropertyCache, self).__init__(
 
74
            proxy_object=proxy_object, *args, **kwargs)
64
75
    
65
76
    def property_changed(self, property=None, value=None):
66
77
        """This is called whenever we get a PropertyChanged signal
85
96
        # Logger
86
97
        self.logger = logger
87
98
        
 
99
        self._update_timer_callback_tag = None
 
100
        self.last_checker_failed = False
 
101
        
88
102
        # The widget shown normally
89
103
        self._text_widget = urwid.Text(u"")
90
104
        # The widget shown when we have focus
106
120
                                     self.got_secret,
107
121
                                     client_interface,
108
122
                                     byte_arrays=True)
109
 
        self.proxy.connect_to_signal(u"NeedApproval",
110
 
                                     self.need_approval,
111
 
                                     client_interface,
112
 
                                     byte_arrays=True)
113
123
        self.proxy.connect_to_signal(u"Rejected",
114
124
                                     self.rejected,
115
125
                                     client_interface,
116
126
                                     byte_arrays=True)
 
127
        last_checked_ok = isoformat_to_datetime(self.properties
 
128
                                                ["last_checked_ok"])
 
129
        if last_checked_ok is None:
 
130
            self.last_checker_failed = True
 
131
        else:
 
132
            self.last_checker_failed = ((datetime.datetime.utcnow()
 
133
                                         - last_checked_ok)
 
134
                                        > datetime.timedelta
 
135
                                        (milliseconds=
 
136
                                         self.properties["interval"]))
 
137
        if self.last_checker_failed:
 
138
            self._update_timer_callback_tag = (gobject.timeout_add
 
139
                                               (1000,
 
140
                                                self.update_timer))
117
141
    
118
142
    def checker_completed(self, exitstatus, condition, command):
119
143
        if exitstatus == 0:
120
 
            #self.logger(u'Checker for client %s (command "%s")'
121
 
            #            u' was successful'
122
 
            #            % (self.properties[u"name"], command))
 
144
            if self.last_checker_failed:
 
145
                self.last_checker_failed = False
 
146
                gobject.source_remove(self._update_timer_callback_tag)
 
147
                self._update_timer_callback_tag = None
 
148
            self.logger(u'Checker for client %s (command "%s")'
 
149
                        u' was successful'
 
150
                        % (self.properties[u"name"], command))
 
151
            self.update()
123
152
            return
 
153
        # Checker failed
 
154
        if not self.last_checker_failed:
 
155
            self.last_checker_failed = True
 
156
            self._update_timer_callback_tag = (gobject.timeout_add
 
157
                                               (1000,
 
158
                                                self.update_timer))
124
159
        if os.WIFEXITED(condition):
125
160
            self.logger(u'Checker for client %s (command "%s")'
126
161
                        u' failed with exit code %s'
127
162
                        % (self.properties[u"name"], command,
128
163
                           os.WEXITSTATUS(condition)))
129
 
            return
130
 
        if os.WIFSIGNALED(condition):
 
164
        elif os.WIFSIGNALED(condition):
131
165
            self.logger(u'Checker for client %s (command "%s")'
132
166
                        u' was killed by signal %s'
133
167
                        % (self.properties[u"name"], command,
134
168
                           os.WTERMSIG(condition)))
135
 
            return
136
 
        if os.WCOREDUMP(condition):
 
169
        elif os.WCOREDUMP(condition):
137
170
            self.logger(u'Checker for client %s (command "%s")'
138
171
                        u' dumped core'
139
172
                        % (self.properties[u"name"], command))
140
 
        self.logger(u'Checker for client %s completed mysteriously')
 
173
        else:
 
174
            self.logger(u'Checker for client %s completed mysteriously')
 
175
        self.update()
141
176
    
142
177
    def checker_started(self, command):
143
 
        #self.logger(u'Client %s started checker "%s"'
144
 
        #            % (self.properties[u"name"], unicode(command)))
145
 
        pass
 
178
        self.logger(u'Client %s started checker "%s"'
 
179
                    % (self.properties[u"name"], unicode(command)))
146
180
    
147
181
    def got_secret(self):
148
182
        self.logger(u'Client %s received its secret'
149
183
                    % self.properties[u"name"])
150
184
    
151
 
    def need_approval(self, timeout, default):
152
 
        if not default:
153
 
            message = u'Client %s needs approval within %s seconds'
154
 
        else:
155
 
            message = u'Client %s will get its secret in %s seconds'
156
 
        self.logger(message
157
 
                    % (self.properties[u"name"], timeout/1000))
158
 
    
159
 
    def rejected(self, reason):
160
 
        self.logger(u'Client %s was rejected; reason: %s'
161
 
                    % (self.properties[u"name"], reason))
 
185
    def rejected(self):
 
186
        self.logger(u'Client %s was rejected'
 
187
                    % self.properties[u"name"])
162
188
    
163
189
    def selectable(self):
164
190
        """Make this a "selectable" widget.
186
212
                          u"bold-underline-blink":
187
213
                              u"bold-underline-blink-standout",
188
214
                          }
189
 
 
 
215
        
190
216
        # Rebuild focus and non-focus widgets using current properties
191
 
 
192
 
        # Base part of a client. Name!
193
 
        self._text = (u'%(name)s: '
194
 
                      % {u"name": self.properties[u"name"]})
195
 
 
196
 
        if self.properties[u"approved_pending"]:
197
 
            if self.properties[u"approved_by_default"]:
198
 
                self._text += u"Connection established to client. (d)eny?"
199
 
            else:
200
 
                self._text += u"Seeks approval to send secret. (a)pprove?"
201
 
        else:
202
 
            self._text += (u'%(enabled)s'
203
 
                           % {u"enabled":
204
 
                               (u"enabled"
205
 
                                if self.properties[u"enabled"]
206
 
                                else u"DISABLED")})
 
217
        self._text = (u'%(name)s: %(enabled)s%(timer)s'
 
218
                      % { u"name": self.properties[u"name"],
 
219
                          u"enabled":
 
220
                              (u"enabled"
 
221
                               if self.properties[u"enabled"]
 
222
                               else u"DISABLED"),
 
223
                          u"timer": (unicode(datetime.timedelta
 
224
                                             (milliseconds =
 
225
                                              self.properties
 
226
                                              [u"timeout"])
 
227
                                             - (datetime.datetime
 
228
                                                .utcnow()
 
229
                                                - isoformat_to_datetime
 
230
                                                (max((self.properties
 
231
                                                 ["last_checked_ok"]
 
232
                                                 or
 
233
                                                 self.properties
 
234
                                                 ["created"]),
 
235
                                                    self.properties[u"last_enabled"]))))
 
236
                                     if (self.last_checker_failed
 
237
                                         and self.properties
 
238
                                         [u"enabled"])
 
239
                                     else u"")})
207
240
        if not urwid.supports_unicode():
208
241
            self._text = self._text.encode("ascii", "replace")
209
242
        textlist = [(u"normal", self._text)]
220
253
        if self.update_hook is not None:
221
254
            self.update_hook()
222
255
    
 
256
    def update_timer(self):
 
257
        "called by gobject"
 
258
        self.update()
 
259
        return True             # Keep calling this
 
260
    
223
261
    def delete(self):
 
262
        if self._update_timer_callback_tag is not None:
 
263
            gobject.source_remove(self._update_timer_callback_tag)
 
264
            self._update_timer_callback_tag = None
224
265
        if self.delete_hook is not None:
225
266
            self.delete_hook(self)
226
267
    
233
274
    def keypress(self, (maxcol,), key):
234
275
        """Handle keys.
235
276
        This overrides the method from urwid.FlowWidget"""
236
 
        if key == u"+":
237
 
            self.proxy.Enable(dbus_interface = client_interface)
238
 
        elif key == u"-":
239
 
            self.proxy.Disable(dbus_interface = client_interface)
240
 
        elif key == u"a":
241
 
            self.proxy.Approve(dbus.Boolean(True, variant_level=1),
242
 
                               dbus_interface = client_interface)
243
 
        elif key == u"d":
244
 
            self.proxy.Approve(dbus.Boolean(False, variant_level=1),
245
 
                                  dbus_interface = client_interface)
 
277
        if key == u"e" or key == u"+":
 
278
            self.proxy.Enable()
 
279
        elif key == u"d" or key == u"-":
 
280
            self.proxy.Disable()
246
281
        elif key == u"r" or key == u"_" or key == u"ctrl k":
247
282
            self.server_proxy_object.RemoveClient(self.proxy
248
283
                                                  .object_path)
249
284
        elif key == u"s":
250
 
            self.proxy.StartChecker(dbus_interface = client_interface)
 
285
            self.proxy.StartChecker()
251
286
        elif key == u"S":
252
 
            self.proxy.StopChecker(dbus_interface = client_interface)
 
287
            self.proxy.StopChecker()
253
288
        elif key == u"C":
254
 
            self.proxy.CheckedOK(dbus_interface = client_interface)
 
289
            self.proxy.CheckedOK()
255
290
        # xxx
256
291
#         elif key == u"p" or key == "=":
257
292
#             self.proxy.pause()
259
294
#             self.proxy.unpause()
260
295
#         elif key == u"RET":
261
296
#             self.open()
262
 
#        elif key == u"+":
263
 
#            self.proxy.Approve(True)
264
 
#        elif key == u"-":
265
 
#            self.proxy.Approve(False)
266
297
        else:
267
298
            return key
268
299
    
565
596
                                             u"r: Remove",
566
597
                                             u"s: Start new checker",
567
598
                                             u"S: Stop checker",
568
 
                                             u"C: Checker OK",
569
 
                                             u"A: Approve",
570
 
                                             u"D: Deny"))))
 
599
                                             u"C: Checker OK"))))
571
600
                self.refresh()
572
601
            elif key == u"tab":
573
602
                if self.topwidget.get_focus() is self.logbox: