]> git.donarmstrong.com Git - infobot.git/blob - src/core.pl
memusage support for open/free/net bsd added. patch from Kuma/Rev
[infobot.git] / src / core.pl
1 #
2 #   core.pl: Important functions stuff...
3 #    Author: dms
4 #   Version: v0.4 (20000718)
5 #   Created: 20000322
6 #
7
8 use strict;
9
10 # dynamic scalar. MUST BE REDUCED IN SIZE!!!
11 ### TODO: reorder.
12 use vars qw(
13         $answer $correction_plausible $talkchannel
14         $statcount $memusage $user $memusageOld $bot_version $dbh
15         $shm $host $msg $bot_misc_dir $bot_pid $bot_base_dir $noreply
16         $bot_src_dir $conn $irc $learnok $nick $ident $no_syscall
17         $force_public_reply $addrchar $userHandle $addressedother
18         $floodwho $chan $msgtime $server $firsttime $wingaterun
19         $flag_quit $msgType
20         $utime_userfile $wtime_userfile $ucount_userfile
21         $utime_chanfile $wtime_chanfile $ucount_chanfile
22 );
23
24 # dynamic hash.
25 use vars qw(@joinchan @ircServers @wingateBad @wingateNow @wingateCache
26 );
27
28 ### dynamic hash. MUST BE REDUCED IN SIZE!!!
29
30 use vars qw(%count %netsplit %netsplitservers %flood %dcc %orig
31             %nuh %talkWho %seen %floodwarn %param %dbh %ircPort
32             %topic %moduleAge %last %time %mask %file
33             %forked %chanconf %channels
34 );
35
36 # Signals.
37 $SIG{'HUP'}  = 'restart'; #  1.
38 $SIG{'INT'}  = 'doExit';  #  2.
39 $SIG{'KILL'} = 'doExit';  #  9. DOES NOT WORK. 'man perlipc' for details.
40 $SIG{'TERM'} = 'doExit';  # 15.
41 $SIG{'__WARN__'} = 'doWarn';
42
43 # initialize variables.
44 $last{buflen}   = 0;
45 $last{say}      = "";
46 $last{msg}      = "";
47 $userHandle     = "default";
48 $msgtime        = time();
49 $wingaterun     = time();
50 $firsttime      = 1;
51 $utime_userfile = 0;
52 $wtime_userfile = 0;
53 $ucount_userfile = 0;
54 $utime_chanfile = 0;
55 $wtime_chanfile = 0;
56 $ucount_chanfile = 0;
57
58 $bot_version    = "blootbot cvs (20010214) -- $^O";
59 $noreply        = "NOREPLY";
60
61 ##########
62 ### misc commands.
63 ###
64
65 sub doExit {
66     my ($sig)   = @_;
67
68     if (defined $flag_quit) {
69         &WARN("doExit: quit already called.");
70         return;
71     }
72     $flag_quit  = 1;
73
74     if (!defined $bot_pid) {    # independent.
75         exit 0;
76     } elsif ($bot_pid == $$) {  # parent.
77         &status("parent caught SIG$sig (pid $$).") if (defined $sig);
78
79         &status("--- Start of quit.");
80
81         &closeDCC();
82         &closePID();
83         &seenFlush();
84         &quit($param{'quitMsg'}) if (&whatInterface() =~ /IRC/);
85         &writeUserFile();
86         &writeChanFile();
87         &uptimeWriteFile()      if (&ChanConfList("uptime"));
88         &closeDB();
89         &closeSHM($shm);
90         &dumpallvars()          if (&IsParam("dumpvarsAtExit"));
91         &closeLog();
92         &closeSQLDebug()        if (&IsParam("SQLDebug"));
93
94         &status("--- QUIT.");
95     } else {                                    # child.
96         &status("child caught SIG$sig (pid $$).");
97     }
98
99     exit 0;
100 }
101
102 sub doWarn {
103     $SIG{__WARN__} = sub { warn $_[0]; };
104
105     foreach (@_) {
106         &WARN("PERL: $_");
107     }
108
109     $SIG{__WARN__} = 'doWarn';  # ???
110 }
111
112 # Usage: &IsParam($param);
113 # blootbot.config specific.
114 sub IsParam {
115     my $param = $_[0];
116
117     return 0 unless (defined $param);
118     return 0 unless (exists $param{$param});
119     return 0 unless ($param{$param});
120     return 0 if $param{$param} =~ /^false$/i;
121     return 1;
122 }
123
124 #####
125 #  Usage: &ChanConfList($param)
126 #  About: gets channels with 'param' enabled. (!!!)
127 # Return: array of channels
128 sub ChanConfList {
129     my $param   = $_[0];
130     return unless (defined $param);
131     my %chan    = &getChanConfList($param);
132
133     # what if we have it set on _default and a few channels with
134     # negative set? perhaps we should disable -blah settings to remove
135     # this mess.
136
137     if (exists $chan{_default}) {
138         return keys %chanconf;
139     } else {
140         ### TODO: -option is included aswell though.
141         return keys %chan;
142     }
143 }
144
145 #####
146 #  Usage: &getChanConfList($param)
147 #  About: gets channels with 'param' enabled, internal use only.
148 # Return: hash of channels
149 sub getChanConfList {
150     my $param   = $_[0];
151     my %chan;
152
153     return unless (defined $param);
154
155     foreach (keys %chanconf) {
156         my $chan        = $_;
157 #       &DEBUG("chan => $chan");
158         my @array       = grep /^$param$/, keys %{ $chanconf{$chan} };
159
160         next unless (scalar @array);
161
162         if (scalar @array > 1) {
163             &WARN("multiple items found?");
164         }
165
166         if ($array[0] eq "0") {
167             $chan{$chan}        = -1;
168         } else {
169             $chan{$chan}        =  1;
170         }
171     }
172
173     return %chan;
174 }
175
176 #####
177 #  Usage: &IsChanConf($param);
178 #  About: Check for 'param' on the basis of channel config.
179 # Return: 1 for enabled, 0 for passive disable, -1 for active disable.
180 sub IsChanConf {
181     my($param)  = shift;
182
183     if (!defined $param) {
184         &WARN("param == NULL.");
185         return 0;
186     }
187
188     ### TODO: VERBOSITY on how chanconf returned 1 or 0 or -1.
189     my %chan    = &getChanConfList($param);
190     if (!defined $msgType) {
191         return $chan{_default} || 0;
192     }
193
194     if ($msgType eq "public") {
195         return $chan{lc $chan} || $chan{_default} || 0;
196     }
197
198     if ($msgType eq "private") {
199         return $chan{_default} || 0;
200     }
201
202 ### debug purposes only.
203 #    &DEBUG("param => $param, msgType => $msgType.");
204 #    foreach (keys %chan) {
205 #       &DEBUG("   $_ => $chan{$_}");
206 #    }
207
208     return 0;
209 }
210
211 #####
212 #  Usage: &getChanConf($param);
213 #  About: Retrieve value for 'param' value in current/default chan.
214 # Return: scalar for success, undef for failure.
215 sub getChanConf {
216     my($param,$chan)    = @_;
217
218     if (!defined $param) {
219         &WARN("param == NULL.");
220         return 0;
221     }
222
223     $chan       ||= "_default";
224     my @c       = grep /^$chan$/i, keys %chanconf;
225
226     if (@c and $c[0] ne $chan) {
227         &WARN("c ne chan ($c[0] ne $chan)");
228     }
229
230     return $chanconf{$c[0] || "_default"}{$param};
231 }
232
233 sub showProc {
234     my ($prefix) = $_[0] || "";
235
236     if (!open(IN, "/proc/$$/status")) {
237         &ERROR("cannot open '/proc/$$/status'.");
238         return;
239     }
240
241     if ($^O eq "linux") {
242         while (<IN>) {
243             $memusage = $1 if (/^VmSize:\s+(\d+) kB/);
244         }
245         close IN;
246
247     } elsif ($^O eq "netbsd") {
248         $memusage = (stat "/proc/$$/mem")[7]/1024;
249
250     } elsif ($^O =~ /^(free|open)bsd$/) {
251         my @info  = split /\s+/, `/bin/ps -l -p $$`;
252         $memusage = $info[20];
253
254     } else {
255         $memusage = "UNKNOWN";
256         return;
257     }
258
259     if (defined $memusageOld and &IsParam("DEBUG")) {
260         # it's always going to be increase.
261         my $delta = $memusage - $memusageOld;
262         my $str;
263         if ($delta == 0) {
264             return;
265         } elsif ($delta > 500) {
266             $str = "MEM:$prefix increased by $delta kB. (total: $memusage kB)";
267         } elsif ($delta > 0) {
268             $str = "MEM:$prefix increased by $delta kB";
269         } else {        # delta < 0.
270             $delta = -$delta;
271             # never knew RSS could decrease, probably Size can't?
272             $str = "MEM:$prefix decreased by $delta kB. YES YES YES";
273         }
274
275         &status($str);
276     }
277     $memusageOld = $memusage;
278 }
279
280 ######
281 ###### SETUP
282 ######
283
284 sub setup {
285     &showProc(" (\&openLog before)");
286     &openLog();         # write, append.
287     &status("--- Started logging.");
288
289     foreach ("debian") {
290         my $dir = "$bot_base_dir/$_/";
291         next if ( -d $dir);
292         &status("Making dir $_");
293         mkdir $dir, 0755;
294     }
295
296     # read.
297     &loadLang($bot_misc_dir.            "/blootbot.lang");
298     &loadIRCServers();
299     &readUserFile();
300     &readChanFile();
301     &loadMyModulesNow();        # must be after chan file.
302
303     $shm = &openSHM();
304     &openSQLDebug()     if (&IsParam("SQLDebug"));
305     &openDB($param{'DBName'}, $param{'SQLUser'}, $param{'SQLPass'});
306
307     &status("Setup: ". &countKeys("factoids") ." factoids.");
308
309     $param{tempDir} =~ s#\~/#$ENV{HOME}/#;
310
311     &status("Initial memory usage: $memusage kB");
312 }
313
314 sub setupConfig {
315     $param{'VERBOSITY'} = 1;
316     &loadConfig($bot_misc_dir."/blootbot.config");
317
318     foreach ("ircNick", "ircUser", "ircName", "DBType", "tempDir") {
319         next if &IsParam($_);
320         &ERROR("Parameter $_ has not been defined.");
321         exit 1;
322     }
323
324     if ($param{tempDir} =~ s#\~/#$ENV{HOME}/#) {
325         &VERB("Fixing up tempDir.",2);
326     }
327
328     if ($param{tempDir} =~ /~/) {
329         &ERROR("parameter tempDir still contains tilde.");
330         exit 1;
331     }
332
333     if (! -d $param{tempDir}) {
334         &status("making $param{tempDir}...");
335         system("mkdir $param{tempDir}");
336     }
337
338     # static scalar variables.
339     $file{utm}  = "$bot_base_dir/$param{'ircUser'}.uptime";
340     $file{PID}  = "$bot_base_dir/$param{'ircUser'}.pid";
341 }
342
343 sub startup {
344     if (&IsParam("DEBUG")) {
345         &status("enabling debug diagnostics.");
346         ### I thought disabling this reduced memory usage by 1000 kB.
347         use diagnostics;
348     }
349
350     $count{'Question'}  = 0;
351     $count{'Update'}    = 0;
352     $count{'Dunno'}     = 0;
353     $count{'Moron'}     = 0;
354 }
355
356 sub shutdown {
357     # reverse order of &setup().
358     &DEBUG("shutdown called.");
359
360     &closeDB();
361     &closeSHM($shm);    # aswell. TODO: use this in &doExit?
362     &closeLog();
363 }
364
365 sub restart {
366     my ($sig) = @_;
367
368     if ($$ == $bot_pid) {
369         &status("--- $sig called.");
370
371         ### crappy bug in Net::IRC?
372         if (!$conn->connected and time - $msgtime > 900) {
373             &status("reconnecting because of uncaught disconnect.");
374 ##          $irc->start;
375             $conn->connect();
376             return;
377         }
378
379         &DCCBroadcast("-HUP called.","m");
380         &shutdown();
381         &loadConfig($bot_misc_dir."/blootbot.config");
382         &reloadAllModules() if (&IsParam("DEBUG"));
383         &setup();
384
385         &status("--- End of $sig.");
386     } else {
387         &status("$sig called; ignoring restart.");
388     }
389 }
390
391 # File: Configuration.
392 sub loadConfig {
393     my ($file) = @_;
394
395     if (!open(FILE, $file)) {
396         &ERROR("FAILED loadConfig ($file): $!");
397         &status("Please copy files/sample.config to files/blootbot.config");
398         &status("  and edit files/blootbot.config, modify to tastes.");
399         exit 0;
400     }
401
402     my $count = 0;
403     while (<FILE>) {
404         chomp;
405         next if /^\s*\#/;
406         next unless /\S/;
407         my ($set,$key,$val) = split(/\s+/, $_, 3);
408
409         if ($set ne "set") {
410             &status("loadConfig: invalid line '$_'.");
411             next;
412         }
413
414         # perform variable interpolation
415         $val =~ s/(\$(\w+))/$param{$2}/g;
416
417         $param{$key} = $val;
418
419         ++$count;
420     }
421     close FILE;
422
423     $file =~ s/^.*\///;
424     &status("Loaded config $file ($count items)");
425 }
426
427 1;