r8451: fix background monitor
[irc-logger.git] / logger.lisp
1 o;;;  -*- Mode: Lisp -*-
2 ;;;; $Id: logger.lisp,v 1.11 2003/12/16 21:19:56 krosenberg Exp $
3 ;;;;
4 ;;;; Purpose: A IRC logging bot 
5 ;;;; Author:  Kevin Rosenberg
6
7 (in-package irc-logger)
8
9 (defvar *daemon-monitor-process* nil "Process of background monitor.")
10
11 (defclass channel ()
12   ((name :initarg :name :reader name
13          :documentation "Name of channel.")
14    (streams :initarg :streams :reader streams
15             :documentation "List of output streams.")
16    (output-root :initarg :output-root :reader output-root)
17    (current-output-names :initarg :current-output-names :accessor current-output-names)))
18
19    
20 (defclass logger ()
21   ((connection :initarg :connection :accessor connection
22                :documentation "IRC connection object.")
23    (handler :initform nil :accessor handler
24             :documentation "Background handler process.")
25    (nick :initarg :nick :reader nickname
26          :documentation "Nickname of the bot.")
27    (password :initarg :password :reader password
28              :documentation "Nickname's nickserver password.")
29    (server :initarg :server :reader server
30            :documentation "Connected IRC server.")
31    (channel-names :initarg :channel-names :accessor channel-names
32                   :documentation "List of channel names.")
33    (realname :initarg :realname :reader realname
34            :documentation "Realname for cl-irc")
35    (username :initarg :username :reader username
36            :documentation "Username for cl-irc")
37    (logging-stream :initarg :logging-stream :reader logging-stream 
38                    :documentation "logging-stream for cl-irc.")
39    (channels :initarg :channels :accessor channels
40              :documentation "List of channels.")
41    (user-output :initarg :user-output :reader user-output
42                 :documentation
43                 "Output parameter from user, maybe stream or pathname.")
44    (unichannel :initarg :unichannel :reader unichannel :type boolean
45                :documentation "T if user-output is directory for individual channel output.")
46    (formats :initarg :formats :reader formats
47                   :documentation
48                   "A list of output formats.")
49    (async :initarg :async :reader async
50                   :documentation
51                   "Whether to use async")
52    (last-pong :initform nil :accessor last-pong
53                   :documentation
54                   "utime of last pong message")
55    (warning-message-utime :initform nil :accessor warning-message-utime
56                   :documentation
57                   "Time of last, potentially active, warning message.")))
58
59 (defvar *loggers* nil "List of active loggers.")
60
61 (defparameter *user-address-scanner*
62   (create-scanner
63    '(:sequence #\!
64      (:register
65       (:greedy-repetition 1 nil :non-whitespace-char-class)))
66    :case-insensitive-mode t))
67
68 (defun find-logger-with-nick (nick)
69   (find nick (the list *loggers*) :test #'string-equal :key #'nickname))
70
71 (defun find-logger-with-connection (conn)
72   (find conn (the list *loggers*) :test #'eq :key #'connection))
73
74 (defun canonicalize-channel-name (name)
75   (string-left-trim '(#\#) name))
76
77 (defun find-channel-with-name (logger name)
78   (find name (the list (channels logger)) :test #'string-equal :key #'name))
79   
80 (defun make-output-name (name year month day)
81     (format nil "~A-~4,'0D.~2,'0D.~2,'0D" (canonicalize-channel-name name)
82             year month day))
83
84 (defun make-output-name-utime (name utime)
85   (multiple-value-bind
86         (second minute hour day-of-month month year day-of-week daylight-p zone)
87       (decode-universal-time utime)
88     (declare (ignore second minute hour day-of-week daylight-p zone))
89     (make-output-name name year month day-of-month)))
90
91 (defgeneric write-file-header (format channel-name stream))
92
93 (defmethod write-file-header ((format t) channel-name stream)
94   (declare (ignore channel-name stream))
95   )
96
97 (defgeneric write-file-footer (format channel-name stream))
98
99 (defmethod write-file-footer ((format t) channel-name stream)
100   (declare (ignore channel-name stream))
101   )
102                                
103 (defun %log-file-path (output-root channel-name year month day type)
104   (make-pathname
105    :defaults output-root
106    :directory (append (pathname-directory output-root)
107                       (list
108                        (string-left-trim '(#\#) channel-name)
109                        (format nil "~4,'0D-~2,'0D" year month)))
110    :name (make-output-name channel-name year month day)
111    :type type))
112
113 (defgeneric log-file-path (output-root channel-name year month day format))
114
115 (defmethod log-file-path (output-root channel-name year month day
116                           (format (eql :raw)))
117   (%log-file-path output-root channel-name year month day "raw"))
118
119 (defmethod log-file-path (output-root channel-name year month day (format (eql :sexp)))
120   (%log-file-path output-root channel-name year month day "sexp"))
121
122 (defmethod log-file-path (output-root channel-name year month day (format (eql :text)))
123   (%log-file-path output-root channel-name year month day "txt"))
124
125 (defmethod log-file-path (output-root channel-name year month day (format string))
126   (%log-file-path output-root channel-name year month day format))
127
128
129 (defun log-file-path-utime (output-root channel-name format utime)
130   (multiple-value-bind
131         (second minute hour day month year day-of-week daylight-p zone)
132       (decode-universal-time utime)
133     (declare (ignore second minute hour day-of-week daylight-p zone))
134     (log-file-path output-root channel-name year month day format)))
135
136 (defun get-stream (channel istream)
137   (elt (streams channel) istream))
138
139 (defun (setf get-stream) (value channel istream)
140   (setf (elt (streams channel) istream) value))
141
142 (defun get-format (logger istream)
143   (elt (formats logger) istream))
144
145 (defun get-output-name (channel istream)
146   (elt (current-output-names channel) istream))
147
148 (defun (setf get-output-name) (value channel istream)
149   (setf (elt (current-output-names channel) istream) value))
150
151 (defun ensure-output-stream-for-unichannel (utime logger channel istream)
152   (let ((name (make-output-name-utime (name channel) utime)))
153     (unless (string= name (get-output-name channel istream))
154       (when (get-stream channel istream)
155         (write-file-footer (get-format logger istream)
156                            (name channel)
157                            (get-stream channel istream))
158         (close (get-stream channel istream)))
159       (setf (get-output-name channel istream) name)
160       (let ((path (log-file-path-utime (output-root channel) (name channel)
161                                        (get-format logger istream) utime)))
162         (unless (probe-file path)
163           (ensure-directories-exist path)
164           (setf (get-stream channel istream)
165                 (open path :direction :output :if-exists :error
166                       :if-does-not-exist :create))
167           (write-file-header (get-format logger istream)
168                              (name channel)
169                               (get-stream channel istream))
170           (close (get-stream channel istream)))
171         (setf (get-stream channel istream)
172               (open path :direction :output :if-exists :append
173                     :if-does-not-exist :error))))))
174
175 (defun ensure-output-stream (utime logger channel istream)
176   "Ensures that *output-stream* is correct."
177   (cond
178    ((streamp (user-output logger))
179     (unless (get-stream channel istream)
180       (setf (get-stream channel istream) (user-output logger))))
181    ((pathnamep (user-output logger))
182     (cond
183      ((unichannel logger)
184       (ensure-output-stream-for-unichannel utime logger channel istream))
185      (t
186       (setf (get-stream channel istream)
187         (open (user-output logger) :direction :output :if-exists :append)))))))
188
189 (defun format-date-time (utime)
190   (multiple-value-bind
191         (second minute hour day-of-month month year day-of-week daylight-p zone)
192       (decode-universal-time utime)
193     (declare (ignore day-of-week daylight-p zone))
194     (format nil "~4,'0D/~2,'0D/~2,'0D ~2,'0D:~2,'0D:~2,'0D" year month day-of-month hour minute second)))
195
196 (defun format-utime (utime)
197   (multiple-value-bind
198         (second minute hour day-of-month month year day-of-week daylight-p zone)
199       (decode-universal-time utime)
200     (declare (ignore day-of-month month year day-of-week daylight-p zone))
201     (format nil "~2,'0D:~2,'0D:~2,'0D" hour minute second)))
202
203 (defun format-utime-short (utime)
204   (multiple-value-bind
205         (second minute hour day-of-month month year day-of-week daylight-p zone)
206       (decode-universal-time utime)
207     (declare (ignore second day-of-month month year day-of-week daylight-p zone))
208     (format nil "~2,'0D:~2,'0D" hour minute)))
209
210 (defun user-address (msg)
211   (let ((split (split *user-address-scanner* (raw-message-string msg)
212                       :with-registers-p t)))
213     (if (second split)
214         (second split)
215         "")))
216
217 (defun need-user-address? (type)
218   (not (or (eq :action type) (eq :privmsg type))))
219
220 (defgeneric %output-event (format stream utime type channel source text msg 
221                            unichannel))
222
223 (defmethod %output-event ((format t) stream utime type channel source text
224                           msg unichannel)
225   (%output-event :raw stream utime type channel source text msg unichannel))
226
227 (defmethod %output-event ((format (eql :raw)) stream utime type channel source
228                           text msg unichannel)
229   (declare (ignore utime type channel source text text unichannel))
230   (when msg
231     (format stream "~S~%" 
232             (string-right-trim '(#\return) (raw-message-string msg)))))
233
234 (defun last-sexp-field (type msg)
235   (cond
236    ((null msg)
237     nil)
238    ((eq type :kick)
239     (trailing-argument msg))
240    ((need-user-address? type)
241     (user-address msg))))
242
243 (defmethod %output-event ((format (eql :sexp)) stream utime type channel source text
244                           msg unichannel)
245   (if unichannel
246       (format stream "(~S ~S ~S ~S ~S)~%" utime type source text (last-sexp-field type msg))
247     (format stream "(~S ~S ~S ~S ~S ~S)~%" utime type source channel text
248             (last-sexp-field type msg))))
249
250 (defmethod %output-event ((format (eql :text)) stream utime type channel source text
251                           msg unichannel)
252   (format stream "~A " (format-utime utime))
253   (when (and (null unichannel) channel)
254     (format stream "[~A] " channel))
255   
256   (let ((user-address (when (and msg (need-user-address? type)) (user-address msg))))
257     (case type
258       (:privmsg
259        (format stream "<~A> ~A" source text))
260       (:action
261        (format stream "*~A* ~A" source text))
262       (:join
263        (format stream "~A [~A] has joined ~A" source user-address channel))
264       (:part
265        (format stream "-!- ~A [~A] has left ~A" source user-address channel))
266       (:nick
267        (format stream "-!- ~A is now known as ~A" source text))
268       (:kick
269        (format stream "-!- ~A [~A] has been kicked from ~A" source user-address channel))
270       (:quit
271        (format stream "-!- ~A [~A] has quit [~A]" source user-address (if text text "")))
272       (:mode
273        (format stream "-!- ~A has set mode ~A"  source text))
274       (:topic
275        (format stream "-!- ~A changed the topic of ~A to: ~A" source channel text))
276       (:notice
277        (format stream "-~A:~A- ~A" source channel text))
278       (:daemon
279        (format stream "-!!!- ~A" text))
280       (:server
281        (format stream "-!!!- server send message ~A" source channel text))
282       (:error
283        (format stream "-!!!- error: ~A ~A" source text))
284       (:kill
285        (format stream "-!!!- kill: ~A ~A" source text))
286       (t
287        (warn "Unhandled msg type ~A." type))))
288   (write-char #\Newline stream))
289
290 (defun output-event-for-a-stream (msg type channel text logger istream)
291   (ensure-output-stream (received-time msg) logger channel istream)
292   (%output-event  (get-format logger istream) (get-stream channel istream)
293                   (received-time msg) type (name channel) (source msg) text msg
294                   (unichannel logger))
295   (force-output (get-stream channel istream)))
296
297 (defun log-daemon-message (logger fmt &rest args)
298   (let ((text (apply #'format nil fmt args))
299         (time (get-universal-time)))
300     (dolist (channel (channels logger))
301       (dotimes (istream (length (formats logger)))
302         (ensure-output-stream time logger channel istream)
303         (%output-event  (get-format logger istream) (get-stream channel istream)
304                         time :daemon nil nil text nil
305                         (unichannel logger))
306         (force-output (get-stream channel istream))))))
307
308 (defvar *msg*)
309 (defun output-event (msg type channel-name &optional text)
310   (setq *msg* msg)
311   (dolist (logger *loggers*)
312     (case type
313       ((:error :server :kill)
314        ;;send to all channels
315        (dolist (channel (channels logger))
316          (dotimes (i (length (formats logger)))
317            (output-event-for-a-stream msg type channel text logger i))))
318       ((:quit :nick)
319        ;; send to all channels that a nickname is joined
320        (let* ((user (find-user (connection logger)
321                                (case type
322                                  (:nick (source msg))
323                                  (:quit (source msg)))))
324               (channels (when user (cl-irc::channels user))))
325          (dolist (channel (mapcar
326                            #'(lambda (name) (find-channel-with-name logger name)) 
327                            (mapcar #'cl-irc::name channels)))
328            (when channel
329              (dotimes (i (length (formats logger)))
330                (output-event-for-a-stream msg type channel text logger i))))))
331       (t
332        ;; msg contains channel name
333        (let* ((channel (find-channel-with-name logger channel-name)))
334          (when channel
335            (dotimes (i (length (formats logger)))
336              (output-event-for-a-stream msg type channel text logger i))))))))
337
338 (defun privmsg-hook (msg)
339   (output-event msg :privmsg (first (arguments msg)) (trailing-argument msg)))
340
341 (defun action-hook (msg)
342   (output-event msg :action (first (arguments msg))
343                 (subseq (trailing-argument msg) 8 
344                         (- (length (trailing-argument msg)) 1))))
345
346 (defun nick-hook (msg)
347   (output-event msg :nick nil (trailing-argument msg)))
348
349 (defun part-hook (msg)
350   (output-event msg :part (first (arguments msg))))
351
352 (defun quit-hook (msg)
353   (output-event msg :quit nil (trailing-argument msg)))
354
355 (defun join-hook (msg)
356   (output-event msg :join (trailing-argument msg)))
357
358 (defun kick-hook (msg)
359   (output-event msg :kick (first (arguments msg))))
360
361 (defun notice-hook (msg)
362   (if (and (string-equal (source msg) "NickServ")
363            (string-equal "owned by someone else" (trailing-argument msg)))
364       (let ((logger (find-logger-with-connection (connection msg))))
365         (if logger
366             (privmsg (connection msg) (source msg) (format nil "IDENTIFY ~A" (password logger)))
367             (warn "NickServ asks for identity with connection not found."))) 
368       (output-event msg :notice (first (arguments msg)) (trailing-argument msg))))
369
370 (defun ping-hook (msg)
371   (let ((logger (find-logger-with-connection (connection msg))))
372     (pong (connection msg) (server logger))
373     (format *standard-output* "Sending pong to ~A~%" (server logger))))
374
375 (defun pong-hook (msg)
376   (let ((logger (find-logger-with-connection (connection msg))))
377     (setf (last-pong logger) (received-time msg))))
378         
379 (defun topic-hook (msg)
380   (output-event msg :topic (first (arguments msg)) (trailing-argument msg)))
381
382 (defun mode-hook (msg)
383   (output-event msg :mode (first (arguments msg)) 
384                 (format nil "~{~A~^ ~}" (cdr (arguments msg)))))
385
386 (defun make-a-channel (name formats output)
387   (make-instance 'channel
388                  :name name
389                  :streams (make-array (length formats) :initial-element nil)
390                  :output-root (when (and (pathnamep output)
391                                          (null (pathname-name output)))
392                                 output)
393                  :current-output-names (make-array (length formats)
394                                                    :initial-element nil)))
395   
396 (defun make-channels (names formats output)
397   (loop for i from 0 to (1- (length names))
398         collect (make-a-channel (elt names i) formats output)))
399
400 (defun is-unichannel-output (user-output)
401   "Returns T if output is setup for a single channel directory structure."
402   (and (pathnamep user-output) (null (pathname-name user-output))))
403
404 (defun do-connect-and-join (nick server username realname logging-stream channels)
405   (let ((conn (connect :nickname nick :server server
406                        :username username :realname realname
407                        :logging-stream logging-stream)))
408     (mapc #'(lambda (channel) (join conn channel)) channels)
409     (add-hook conn 'irc::irc-privmsg-message 'privmsg-hook)
410     (add-hook conn 'irc::ctcp-action-message 'action-hook)
411     (add-hook conn 'irc::irc-nick-message 'nick-hook)
412     (add-hook conn 'irc::irc-part-message 'part-hook)
413     (add-hook conn 'irc::irc-quit-message 'quit-hook)
414     (add-hook conn 'irc::irc-join-message 'join-hook)
415     (add-hook conn 'irc::irc-kick-message 'kick-hook)
416     (add-hook conn 'irc::irc-mode-message 'mode-hook)
417     (add-hook conn 'irc::irc-topic-message 'topic-hook)
418     (add-hook conn 'irc::irc-notice-message 'notice-hook)
419     (add-hook conn 'irc::irc-rpl_killdone-message 'warning-hook)
420     (add-hook conn 'irc::irc-rpl_closing-message 'warning-hook)
421     (add-hook conn 'irc::irc-error-message 'error-hook)
422     (add-hook conn 'irc::irc-ping-message 'ping-hook)
423     (add-hook conn 'irc::irc-pong-message 'pong-hook)
424     (add-hook conn 'irc::irc-kill-message 'kill-hook)
425     conn))
426
427 (defun create-logger (nick server &key channels output password
428                                        realname username async
429                                        (logging-stream t) (formats '(:text)))
430   "OUTPUT may be a pathname or a stream"
431   ;; check arguments
432   (assert formats)
433   (if (and channels (atom channels))
434       (setq channels (list channels)))
435   (if (atom formats)
436       (setq formats (list formats)))
437   (if (stringp output)
438       (setq output (parse-namestring output)))
439   (let* ((conn (do-connect-and-join nick server username realname logging-stream channels))
440          (logger (make-instance
441                   'logger
442                   :connection conn
443                   :nick nick
444                   :password password
445                   :server server
446                   :channels (make-channels channels formats output)
447                   :channel-names channels
448                   :username username
449                   :realname realname
450                   :async async
451                   :logging-stream logging-stream
452                   :user-output output
453                   :formats formats
454                   :unichannel (is-unichannel-output output))))
455     (unless *daemon-monitor-process*
456       (setq *daemon-monitor-process* (cl-irc::start-process 'daemon-monitor "logger-monitor")))
457     logger))
458
459 (defun start-logger (logger async)
460   (if async
461       (setf (handler logger)
462         (start-background-message-handler (connection logger)))
463       (read-message-loop (connection logger))))
464
465 (defun remove-logger (nick)
466   "Quit the active connection with nick and remove from active list."
467   (let ((logger (find-logger-with-nick nick)))
468     (cond
469       ((null logger)
470        (warn "No active connection found with nick ~A." nick)
471        nil)
472       (t
473        (ignore-errors (irc:quit (connection logger) ""))
474        (stop-background-message-handler (handler logger))
475        (sleep 1)
476        (dolist (channel (channels logger))
477          (let ((c (connection logger)))
478            (when c
479              (ignore-errors (remove-channel c (find-channel c (name channel)))))))
480        (setq *loggers*
481              (delete nick *loggers*  :test #'string-equal :key #'nickname))
482        t))))
483
484 (defun add-logger (nick server &key channels output (password "")
485                                     realname username
486                                     (logging-stream t) (async t) (formats '(:text)))
487   (when (find-logger-with-nick nick)
488     (warn "Closing previously active connection.")
489     (ignore-errors (remove-logger nick)))
490   (let ((logger (create-logger nick server :channels channels :output output
491                                :logging-stream logging-stream :password password
492                                :realname realname :username username
493                                :formats formats
494                                :async async)))
495     (push logger *loggers*)
496     (start-logger logger async)
497     logger))
498
499 (defun add-channel-logger (logger channel-name)
500   (cond
501     ((find-channel-with-name logger channel-name)
502      (warn "Channel ~A already in logger ~A." channel-name logger)
503      nil)
504     (t
505      (let ((channel (make-a-channel channel-name (formats logger) (user-output logger))))
506        (join (connection logger) channel-name)
507        (push channel (channels logger))
508        (push channel-name (channel-names logger))))))
509
510 (defun remove-channel-logger (logger channel-name)
511   (let ((channel (find-channel-with-name logger channel-name)))
512     (cond
513       (channel
514        (part (connection logger) channel-name)
515        (dotimes (i (length (streams channel)))
516          (when (streamp (get-stream channel i))
517            (close (get-stream channel i))
518            (setf (get-stream channel i) nil)))
519        (setf (channels logger) (delete channel-name (channels logger)
520                                        :test #'string-equal
521                                        :key #'name))
522        (setf (channel-names logger) (delete channel-name (channel-names logger)
523                                             :test #'string-equal))
524        t)
525       (t
526        (warn "Channel name ~A not found in logger ~A." 
527              channel-name logger)
528        nil))))
529
530 (defun add-hook-logger (logger class hook)
531   (add-hook (connection logger) class hook))
532
533 (defun remove-hook-logger (logger class hook)
534   (remove-hook (connection logger) class hook))
535
536 (defvar *warning-message-utime* nil)
537
538 (defun kill-hook (msg)
539   (let ((target (second (arguments msg)))
540         (logger (find-logger-with-connection (connection msg))))
541     (when (and (stringp target)
542                (string-equal target (nickname logger)))
543       (setf (warning-message-utime logger) (received-time msg)))
544     (output-event msg :kill nil (format nil "~{~A~^ ~}" (arguments msg)))))
545
546 (defun error-hook (msg)
547   (let ((text (trailing-argument msg))
548         (logger (find-logger-with-connection (connection msg))))
549     (when (and (stringp text) 
550                (zerop (search (format nil "Closing Link: ~A" (nickname logger)) text)))
551       (setf (warning-message-utime logger) (received-time msg)))
552     (output-event msg :error nil (trailing-argument msg))))
553
554 (defun warning-hook (msg)
555   (let ((logger (find-logger-with-connection (connection msg))))
556     (output-event msg :server 
557                   (format nil "~{~A~^ ~} ~A)"
558                           (arguments msg)
559                           (trailing-argument msg)))
560     (when logger
561       (setf (warning-message-utime logger) (get-universal-time)))))
562   
563 (defun daemon-sleep (seconds)
564   #-allegro (sleep seconds)
565   #+allegro (mp:process-sleep seconds))
566
567 (defun log-disconnection (logger)
568   ;; avoid generating too many reconnect messages in the logs
569   (when (or (null (warning-message-utime logger))
570             (< (- (get-universal-time) (warning-message-utime logger)) 300))
571     (log-daemon-message logger "Disconnected. Attempting reconnection at ~A."
572                         (format-date-time (get-universal-time)))))
573
574 (defun log-reconnection (logger)
575   (log-daemon-message logger
576                       "Connection restablished at ~A." (format-date-time (get-universal-time))))
577
578 (defun is-connected (logger)
579   (when (ignore-errors (ping (connection logger) (server logger)))
580     (dotimes (i 20)
581       (when (and (last-pong logger)
582                  (< (- (get-universal-time) (last-pong logger)) 21))
583         (return-from is-connected t))
584       (sleep 1))))
585
586
587 (let (*recon-nick* *recon-server* *recon-username* *recon-realname*
588       *recon-user-output*
589       *recon-formats* *recon-async* *recon-logging-stream* *recon-channel-names*)
590   (declare (special *recon-nick* *recon-server* *recon-username* *recon-realname*
591                     *recon-formats* *recon-password* *recon-async* 
592                     *recon-user-output*
593                     *recon-logging-stream* *recon-channel-names*))
594   
595   (defun attempt-reconnection (logger)
596     (when (is-connected logger)
597       (return-from attempt-reconnection nil))
598     
599     (log-disconnection logger)
600     (when (connection logger)
601       (ignore-errors (quit (connection logger) "Client terminated by server"))
602       (setf *recon-nick* (nickname logger)
603             *recon-server* (server logger)
604             *recon-username* (username logger)
605             *recon-realname* (realname logger)
606             *recon-password* (password logger)
607             *recon-async* (async logger)
608             *recon-user-output* (user-output logger)
609             *recon-formats* (formats logger)
610             *recon-logging-stream* (logging-stream logger)
611             *recon-channel-names* (channel-names logger))
612       (ignore-errors (remove-logger logger)))
613     
614     (ignore-errors
615      (add-logger *recon-nick* *recon-server*
616                  :channels *recon-channel-names*
617                  :output *recon-user-output*
618                  :password *recon-password*
619                  :realname *recon-realname*
620                  :username *recon-username*
621                  :logging-stream *recon-logging-stream*
622                  :async *recon-async*
623                  :formats *recon-formats*)))
624   )
625
626 (defun daemon-monitor ()
627   "This function runs in the background and monitors the connection of the logger."
628   ;; run forever
629   (do ()
630       ()
631     (block main-loop
632       (dolist (logger *loggers*)
633         (do ((warning-time (warning-message-utime logger) (warning-message-utime logger)))
634             ((or (is-connected logger) (null warning-time)))
635           (cond
636            ((and warning-time (> (- (get-universal-time) warning-time) 180))
637             ;;give up frequent checking because no disconnection despite waiting
638             (setf (warning-message-utime logger) nil))
639            ((not (is-connected logger))
640             (unless warning-time
641               (setf (warning-message-utime logger) (get-universal-time)))
642             (attempt-reconnection logger)
643             ;;after a succesful reconnection, the value of logger will be invalid 
644             (sleep 30)
645             (return-from main-loop))
646            (t
647             (daemon-sleep 30)))))
648       (do ((i 0 (1+ i)))
649           ((or (>= i 20) (some (lambda (logger) (warning-message-utime logger)) *loggers*))) 
650         (daemon-sleep 15)))))
651