]> git.donarmstrong.com Git - infobot.git/blob - src/IRC/Schedulers.pl
one too many parens for seen stats; cleanup.
[infobot.git] / src / IRC / Schedulers.pl
1 #
2 # ProcessExtra.pl: Extensions to Process.pl
3 #          Author: dms
4 #         Version: v0.4b (20000923)
5 #         Created: 20000117
6 #
7
8 if (&IsParam("useStrict")) { use strict; }
9
10 sub setupSchedulers {
11     &VERB("Starting schedulers...",2);
12
13     # ONCE OFF.
14
15     # REPETITIVE.
16     &uptimeCycle(1)     if (&IsParam("uptime"));
17     &randomQuote(1)     if (&IsParam("randomQuote"));
18     &randomFactoid(1)   if (&IsParam("randomFactoid"));
19     &logCycle(1)        if ($loggingstatus and &IsParam("logFile") and &IsParam("maxLogSize"));
20     &limitCheck(1)      if (&IsParam("limitcheck"));
21     &netsplitCheck(1);  # mandatory
22     &floodCycle(1);     # mandatory
23     &seenFlush(1)       if (&IsParam("seen") and &IsParam("seenFlushInterval"));
24     &leakCheck(1);      # mandatory
25     &ignoreListCheck(1);# mandatory
26     &seenFlushOld(1)    if (&IsParam("seen"));
27     &ircCheck(1);       # mandatory
28     &miscCheck(1);      # mandatory
29     &shmFlush(1);       # mandatory
30     &slashdotCycle(1)   if (&IsParam("slashdot") and &IsParam("slashdotAnnounce"));
31     &freshmeatCycle(1)  if (&IsParam("freshmeat") and &IsParam("freshmeatAnnounce"));
32     &kernelCycle(1)     if (&IsParam("kernel") and &IsParam("kernelAnnounce"));
33     &wingateWriteFile(1) if (&IsParam("wingate"));
34     &factoidCheck(1)    if (&IsParam("factoidDeleteDelay"));
35 }
36
37 sub ScheduleThis {
38     my ($interval, $codename, @args) = @_;
39     my $waittime = &getRandomInt($interval);
40
41     &VERB("Scheduling \&$codename() for ".&Time2String($waittime),3);
42     $conn->schedule($waittime, \&$codename, @args);
43 }
44
45 sub randomQuote {
46     my $line = &getRandomLineFromFile($bot_misc_dir. "/blootbot.randtext");
47     if (!defined $line) {
48         &ERROR("random Quote: weird error?");
49         return;
50     }
51
52     my @channels = split(/[\s\t]+/, lc $param{'randomQuoteChannels'});
53     @channels    = keys(%channels) unless (scalar @channels);
54
55     my $good = 0;
56     foreach (@channels) {
57         next unless (&validChan($_));
58
59         &status("sending random Quote to $_.");
60         &action($_, "Ponders: ".$line);
61         $good++;
62     }
63
64     if (!$good) {
65         &WARN("randomQuote: no valid channels?");
66         return;
67     }
68
69     my $interval = $param{'randomQuoteInterval'} || 60;
70     &ScheduleThis($interval, "randomQuote") if (@_);
71 }
72
73 sub randomFactoid {
74     my ($key,$val);
75     my $error = 0;
76     while (1) {
77         ($key,$val) = &randKey("factoids","factoid_key,factoid_value");
78 ###     $val =~ tr/^[A-Z]/[a-z]/;       # blah is Good => blah is good.
79         last if ($val !~ /^</);
80         $error++;
81         if ($error == 5) {
82             &ERROR("rF: tried 5 times but failed.");
83             return;
84         }
85     }
86
87     my @channels = split(/[\s\t]+/, lc $param{'randomFactoidChannels'});
88     @channels    = keys(%channels) unless (scalar @channels);
89
90     my $good = 0;
91     foreach (@channels) {
92         next unless (&validChan($_));
93
94         &status("sending random Factoid to $_.");
95 ###     &msg($_, "$key is $val");
96         &action($_, "Thinks: \037$key\037 is $val");
97         ### FIXME: Use &getReply() on above to format factoid properly?
98         $good++;
99     }
100
101     if (!$good) {
102         &WARN("randomFactoid: no valid channels?");
103         return;
104     }
105
106     my $interval = $param{'randomFactoidInterval'} || 60;
107     &ScheduleThis($interval, "randomFactoid") if (@_);
108 }
109
110 sub logCycle {
111     # check if current size is too large.
112     if ( -s $file{log} > $param{'maxLogSize'}) {
113         my $date = sprintf("%04d%02d%02d", (localtime)[5,4,3]);
114         $file{log} = $param{'logfile'} ."-". $date;
115         &status("cycling log file.");
116
117         if ( -e $file{log}) {
118             my $i = 1;
119             my $newlog;
120             while () {
121                 $newlog = $file{log}."-".$i;
122                 last if (! -e $newlog);
123                 $i++;
124             }
125             $file{log} = $newlog;
126         }
127
128         &closeLog();
129         system("/bin/mv '$param{'logfile'}' '$file{log}'");
130         &compress($file{log});
131         &openLog();
132         &status("cycling log file.");
133     }
134
135     # check if all the logs exceed size.
136     my $logdir = "$bot_base_dir/log/";
137     if (opendir(LOGS, $logdir)) {
138         my $tsize = 0;
139         my (%age, %size);
140
141         while (defined($_ = readdir LOGS)) {
142             my $logfile = "$logdir/$_";
143
144             next unless ( -f $logfile);
145             my $size = -s $logfile;
146             my $age = (stat $logfile)[9]; ### or 8 ?
147
148             $age{$age}          = $logfile;
149             $size{$logfile}     = $size;
150
151             $tsize              += $size;
152         }
153         closedir LOGS;
154
155         my $delete = 0;
156         while ($tsize > $param{'maxLogSize'}) {
157             &status("LOG: current size > max ($tsize > $param{'maxLogSize'})");
158             my $oldest = (sort {$a <=> $b} keys %age)[0];
159             &status("LOG: unlinking $age{$oldest}.");
160             ### NOT YET.
161             # unlink $age{$oldest};
162             $tsize -= $oldest;
163             $delete++;
164         }
165
166         ### TODO: add how many b,kb,mb removed?
167         &status("LOG: removed $delete logs.") if ($delete);
168     } else {
169         &WARN("could not open dir $logdir");
170     }
171
172     &ScheduleThis(60, "logCycle") if (@_);
173 }
174
175 sub seenFlushOld {
176     my $max_time = $param{'seenMaxDays'}*60*60*24;
177     my $delete   = 0;
178
179     if ($param{'DBType'} =~ /^pg|postgres|mysql/i) {
180         my $query = "SELECT nick,time FROM seen GROUP BY nick HAVING UNIX_TIMESTAMP() - time > $max_time";
181         my $sth = $dbh->prepare($query);
182         $sth->execute;
183
184         while (my @row = $sth->fetchrow_array) {
185             my ($nick,$time) = @row;
186
187             &dbDel("seen","nick",$nick);
188             $delete++;
189         }
190         $sth->finish;
191     } elsif ($param{'DBType'} =~ /^dbm/i) {
192         my $time = time();
193
194         foreach (keys %seen) {
195             my $delta_time = $time - &dbGet("seen", "NULL", $_, "time");
196             next unless ($delta_time > $max_time);
197
198             &DEBUG("seenFlushOld: ".&Time2String($delta_time) );
199             delete $seen{$_};
200             $delete++;
201         }
202     } else {
203         &FIXME("seenFlushOld: for PG/NO-DB.");
204     }
205     &VERB("SEEN deleted $delete seen entries.",2);
206
207     &ScheduleThis(1440, "seenFlushOld") if (@_);
208 }
209
210 sub limitCheck {
211     my $limitplus = $param{'limitcheckPlus'} || 5;
212
213     if (scalar keys %netsplit) {
214         &status("limitcheck: netsplit active.");
215         return;
216     }
217
218     my @channels = split(/[\s\t]+/, lc $param{'limitcheck'});
219
220     foreach (@channels) {
221         next unless (&validChan($_));
222
223         if (!exists $channels{$_}{'o'}{$ident}) {
224             &ERROR("limitcheck: dont have ops on $_.");
225             next;
226         }
227
228         my $newlimit = scalar(keys %{$channels{$_}{''}}) + $limitplus;
229         my $limit = $channels{$_}{'l'};
230
231         next unless (!defined $limit or $limit != $newlimit);
232
233         &rawout("MODE $_ +l $newlimit");
234     }
235
236     my $interval = $param{'limitcheckInterval'} || 10;
237     &ScheduleThis($interval, "limitCheck") if (@_);
238 }
239
240 sub netsplitCheck {
241     my ($s1,$s2);
242
243     foreach $s1 (keys %netsplitservers) {
244         foreach $s2 (keys %{$netsplitservers{$s1}}) {
245             if (time() - $netsplitservers{$s1}{$s2} > 3600) {
246                 &status("netsplit between $s1 and $s2 appears to be stale.");
247                 delete $netsplitservers{$s1}{$s2};
248             }
249         }
250     }
251
252     # %netsplit hash checker.
253     foreach (keys %netsplit) {
254         if (&IsNickInAnyChan($_)) {
255             &DEBUG("netsplitC: $_ is in some chan; removing from netsplit list.");
256             delete $netsplit{$_};
257         }
258         next unless (time() - $netsplit{$_} > 60*60*2); # 2 hours.
259         next if (&IsNickInAnyChan($_));
260
261         &DEBUG("netsplitC: $_ didn't come back from netsplit in 2 hours; removing from netsplit list.");
262         delete $netsplit{$_};
263     }
264
265     &ScheduleThis(30, "netsplitCheck") if (@_);
266 }
267
268 sub floodCycle {
269     my $interval = $param{'floodInterval'} || 60;       # seconds.
270     my $delete = 0;
271
272     my $who;
273     foreach $who (keys %flood) {
274         foreach (keys %{$flood{$who}}) {
275             if (time() - $flood{$who}{$_} > $interval) {
276                 delete $flood{$who}{$_};
277                 $delete++;
278             }
279         }
280     }
281     &VERB("floodCycle: deleted $delete items.",2);
282
283     &ScheduleThis($interval, "floodCycle") if (@_);     # minutes.
284 }
285
286 sub seenFlush {
287     my $nick;
288     my $flushed = 0;
289     my %stats;
290     $stats{'count_old'} = &countKeys("seen");
291     $stats{'new'}       = 0;
292     $stats{'old'}       = 0;
293
294     if ($param{'DBType'} =~ /^mysql|pg|postgres/i) {
295         foreach $nick (keys %seencache) {
296             my $exists = &dbGet("seen","nick", $nick, "nick");
297
298             if (defined $exists and $exists) {
299                 &dbUpdate("seen", "nick", $nick, (
300                         "time" => $seencache{$nick}{'time'},
301                         "host" => $seencache{$nick}{'host'},
302                         "channel" => $seencache{$nick}{'chan'},
303                         "message" => $seencache{$nick}{'msg'},
304                 ) );
305                 $stats{'old'}++;
306             } else {
307                 my $retval = &dbInsert("seen", $nick, (
308                         "nick" => $seencache{$nick}{'nick'},
309                         "time" => $seencache{$nick}{'time'},
310                         "host" => $seencache{$nick}{'host'},
311                         "channel" => $seencache{$nick}{'chan'},
312                         "message" => $seencache{$nick}{'msg'},
313                 ) );
314                 $stats{'new'}++;
315
316                 ### TODO: put bad nick into a list and don't do it again!
317                 &FIXME("Should never happen! (nick => $nick)") if !$retval;
318             }
319
320             delete $seencache{$nick};
321             $flushed++;
322         }
323
324     } elsif ($param{'DBType'} =~ /^dbm/i) {
325
326         foreach $nick (keys %seencache) {
327             my $retval = &dbInsert("seen", $nick, (
328                 "nick" => $seencache{$nick}{'nick'},
329                 "time" => $seencache{$nick}{'time'},
330                 "host" => $seencache{$nick}{'host'},
331                 "channel" => $seencache{$nick}{'chan'},
332                 "message" => $seencache{$nick}{'msg'},
333             ) );
334
335             ### TODO: put bad nick into a list and don't do it again!
336             &FIXME("Should never happen! (nick => $nick)") if !$retval;
337
338             delete $seencache{$nick};
339             $flushed++;
340         }
341     } else {
342         &DEBUG("seenFlush: NO VALID FACTOID SUPPORT?");
343     }
344
345     &status("Flushed $flushed seen entries.")           if ($flushed);
346     &VERB(sprintf("  new seen: %03.01f%% (%d/%d)",
347         $stats{'new'}*100/$stats{'count_old'},
348         $stats{'new'}, $stats{'count_old'} ), 2)        if ($stats{'new'});
349     &VERB(sprintf("  now seen: %3.1f%% (%d/%d)",
350         $stats{'old'}*100/&countKeys("seen"),
351         $stats{'old'}, &countKeys("seen") ), 2)         if ($stats{'old'});
352
353     &WARN("scalar keys seenflush != 0!")        if (scalar keys %seenflush);
354
355     my $interval = $param{'seenFlushInterval'} || 60;
356     &ScheduleThis($interval, "seenFlush") if (@_);
357 }
358
359 sub leakCheck {
360     my ($blah1,$blah2);
361     my $count = 0;
362
363     # flood.
364     foreach $blah1 (keys %flood) {
365         foreach $blah2 (keys %{$flood{$blah1}}) {
366             $count += scalar(keys %{$flood{$blah1}{$blah2}});
367         }
368     }
369     &VERB("\%flood has $count total keys.",2);
370
371     my $chan;
372     foreach $chan (grep /[A-Z]/, keys %channels) {
373         &DEBUG("leak: chan => '$chan'.");
374         my ($i,$j);
375         foreach $i (keys %{$channels{$chan}}) {
376             foreach (keys %{$channels{$chan}{$i}}) {
377                 &DEBUG("leak:   \$channels{$chan}{$i}{$_} ...");
378             }
379         }
380     }
381
382     &ScheduleThis(60, "leakCheck") if (@_);
383 }
384
385 sub ignoreListCheck {
386     my $time = time();
387     my $count = 0;
388
389     foreach (keys %ignoreList) {
390         next if ($ignoreList{$_} == 1);
391         next unless ($time > $ignoreList{$_});
392
393         delete $ignoreList{$_};
394         &status("ignore: $_ has expired.");
395         $count++;
396     }
397     &VERB("ignore: $count items deleted.",2);
398
399     &ScheduleThis(30, "ignoreListCheck") if (@_);
400 }
401
402 sub ircCheck {
403     my @array = split /[\t\s]+/, $param{'join_channels'};
404     my $iconf = scalar(@array);
405     my $inow  = scalar(keys %channels);
406     if ($iconf > 2 and $inow * 2 <= $iconf) {
407         &FIXME("ircCheck: current channels * 2 <= config channels. FIXME.");
408     }
409
410     if (!$conn->connected and time - $msgtime > 3600) {
411         &WARN("ircCheck: no msg for 3600 and disco'd! reconnecting!");
412         $msgtime = time();      # just in case.
413         &ircloop();
414     }
415
416     if ($ident !~ /^\Q$param{ircNick}\E$/) {
417         &WARN("ircCheck: ident($ident) != param{ircNick}($param{IrcNick}).");
418     }
419
420     &joinNextChan();
421         # if scalar @joinnext => join more channels
422         # else check for chanserv.
423
424     if (grep /^\s*$/, keys %channels) {
425         &WARN("we have a NULL chan in hash channels? removing!");
426         delete $channels{''};
427         &status("channels now:");
428         foreach (keys %channels) {
429             &status("  $_");
430         }
431     }
432
433
434     &ScheduleThis(240, "ircCheck") if (@_);
435 }
436
437 sub miscCheck {
438     # SHM check.
439     my @ipcs;
440     if ( -x "/usr/bin/ipcs") {
441         @ipcs = `/usr/bin/ipcs`;
442     } else {
443         &WARN("ircCheck: no 'ipcs' binary.");
444     }
445
446     # shmid stale remove.
447     foreach (@ipcs) {
448         chop;
449
450         # key, shmid, owner, perms, bytes, nattch
451         next unless (/^(0x\d+) (\d+)\s+(\S+)\s+(\d+)\s+(\d+)\s+/);
452
453         my ($shmid, $size) = ($2,$5);
454         next unless ($shmid != $shm and $size == 2000);
455
456         &status("SHM: nuking shmid $shmid");
457         system("/usr/bin/ipcrm shm $shmid >/dev/null");
458     }
459
460     ### check modules if they've been modified. might be evil.
461     &reloadAllModules();
462
463     &ScheduleThis(240, "miscCheck") if (@_);
464 }
465
466 sub shmFlush {
467     my $shmmsg = &shmRead($shm);
468     $shmmsg =~ s/\0//g;         # remove padded \0's.
469
470     foreach (split '\|\|', $shmmsg) {
471         &VERB("shm: Processing '$_'.",2);
472
473         if (/^DCC SEND (\S+) (\S+)$/) {
474             my ($nick,$file) = ($1,$2);
475             if (exists $dcc{'SEND'}{$who}) {
476                 &msg($nick,"DCC already active.");
477             } else {
478                 &DEBUG("shm: dcc sending $2 to $1.");
479                 $conn->new_send($1,$2);
480                 $dcc{'SEND'}{$who} = time();
481             }
482         } elsif (/^DELETE FORK (\S+)$/) {
483             delete $forked{$1};
484         } elsif (/^EVAL (.*)$/) {
485             &DEBUG("evaling '$1'.");
486             eval $1;
487         } else {
488             &DEBUG("shm: unknown msg. ($_)");
489         }
490     }
491
492     &shmWrite($shm,"") if ($shmmsg ne "");
493
494     &ScheduleThis(5, "shmFlush") if (@_);
495 }
496
497 sub getNickInUse {
498     if ($ident eq $param{'ircNick'}) {
499         &status("okay, got my nick back.");
500         return;
501     }
502
503     &status("Trying to get my nick back.");
504     &nick($param{'ircNick'});
505
506     &ScheduleThis(5, "getNickInUse") if (@_);
507 }
508
509 sub uptimeCycle {
510     &uptimeWriteFile();
511
512     &ScheduleThis(60, "uptimeCycle") if (@_);
513 }
514
515 sub slashdotCycle {
516     &Forker("slashdot", sub { &Slashdot::slashdotAnnounce(); } );
517
518     &ScheduleThis(60, "slashdotCycle") if (@_);
519 }
520
521 sub freshmeatCycle {
522     &Forker("freshmeat", sub { &Freshmeat::freshmeatAnnounce(); } );
523
524     &ScheduleThis(60, "freshmeatCycle") if (@_);
525 }
526
527 sub kernelCycle {
528     &Forker("kernel", sub { &Kernel::kernelAnnounce(); } );
529
530     &ScheduleThis(240, "kernelCycle") if (@_);
531 }
532
533 sub wingateCheck {
534     return unless &IsParam("wingate");
535     return unless ($param{'wingate'} =~ /^(.*\s+)?$chan(\s+.*)?$/i);
536
537     ### FILE CACHE OF OFFENDING WINGATES.
538     foreach (grep /^$host$/, @wingateBad) {
539         &status("Wingate: RUNNING ON $host BY $who");
540         &ban("*!*\@$host", "") if &IsParam("wingateBan");
541
542         next unless (&IsParam("wingateKick"));
543         &kick($who, "", $param{'wingateKick'})
544     }
545
546     ### RUN CACHE OF TRIED WINGATES.
547     if (grep /^$host$/, @wingateCache) {
548         push(@wingateNow, $host);       # per run.
549         push(@wingateCache, $host);     # cache per run.
550     } else {
551         &DEBUG("Already scanned $host. good.");
552     }
553
554     my $interval = $param{'wingateInterval'} || 60;     # seconds.
555     return if (defined $forked{'wingate'});
556     return if (time() - $wingaterun <= $interval);
557     return unless (scalar(keys %wingateToDo));
558
559     $wingaterun = time();
560
561     &Forker("wingate", sub { &Wingate::Wingates(keys %wingateToDo); } );
562     undef @wingateNow;
563 }
564
565 ### TODO.
566 sub wingateWriteFile {
567     return unless (scalar @wingateCache);
568
569     my $file = "$bot_base_dir/$param{'ircUser'}.wingate";
570     if ($bot_pid != $$) {
571         &DEBUG("wingateWriteFile: Reorganising!");
572
573         open(IN, $file);
574         while (<IN>) {
575             chop;
576             push(@wingateNow, $_);
577         }
578         close IN;
579
580         # very lame hack.
581         my %hash = map { $_ => 1 } @wingateNow;
582         @wingateNow = sort keys %hash;
583     }
584
585     &DEBUG("wingateWF: writing...");
586     open(OUT, ">$file");
587     foreach (@wingateNow) {
588         print OUT "$_\n";
589     }
590     close OUT;
591
592     &ScheduleThis(60, "wingateWriteFile") if (@_);
593 }
594
595 sub factoidCheck {
596     my @list = &searchTable("factoids", "factoid_key", "factoid_key", " #DEL#");
597     my $stale = $param{'factoidDeleteDelay'}*60*60*24;
598
599     foreach (@list) {
600         my $age = &getFactInfo($_, "modified_time");    
601         next unless (time() - $age > $stale);
602
603         my $fix = $_;
604         $fix =~ s/ #DEL#$//g;
605         &VERB("safedel: Removing $fix for good.",2);
606         &delFactoid($_);
607     }
608
609     &ScheduleThis(1440, "factoidCheck") if (@_);
610 }
611
612 sub schedulerSTUB {
613
614     &ScheduleThis(TIME_IN_MINUTES, "FUNCTION") if (@_);
615 }
616
617 1;