55f8c9ea02423b6ca849237ef3cd5ab56ef226d9
[mom.git] / pl_mom.pl
1 #!/usr/bin/perl -w
2
3 use POSIX qw(setsid);
4 use Sys::Syslog;
5 use Sys::Hostname;
6 #use LWP::Simple;
7
8 $debug = 0;
9 $proc = "pl_mom";
10 $alias_addr = "pl-mom\@planet-lab.org";
11 $from_addr = "support\@planet-lab.org";
12 $bwcap = "1.5Mbit";
13
14 if (! $debug) {
15     $kill_thresh = 90;
16     $reboot_thresh = 95;
17     $log_thresh = 85;
18     $change_thresh = 5;
19     $min_thresh = 10;
20     #$byte_cutoff = 16000000000;    # 16GB
21     $byte_cutoff = 5000000000;    # 5GB
22     $bwmon_sleep = 900;
23
24     $sendmail = "/usr/sbin/sendmail -t -f$from_addr";
25     $pidfile = "/var/run/$proc.pid";
26     $rebootfile = "/var/lib/misc/pl_mom.reboot";
27     $daily_log = "/var/lib/misc/pl_mom.daily";
28     $daily_stamp = "/var/lib/misc/pl_mom.stamp";
29 } else {
30     $kill_thresh = 2;
31     $reboot_thresh = 20;
32     $log_thresh = 2;
33     $change_thresh = 5;
34     $min_thresh = 10;
35     $byte_cutoff = 16000;
36     $bwmon_sleep = 10;
37
38     $sendmail = "cat";
39     $pidfile = "./$proc.pid";
40     $rebootfile = "./pl_mom.reboot";
41     $daily_log = "./pl_mom.daily";
42     $daily_stamp = "./pl_mom.stamp";
43 }
44
45 $sleep = 30;
46
47 # daemonize the program
48 if (! $debug) {
49     &daemonize;
50 }
51
52 system("echo $$ > $pidfile");
53
54 # Check to see whether pl_mom rebooted the node
55 if (-e $rebootfile) {
56     unlink($rebootfile);
57     syslog ("warning", "pl_mom: Sending shutdown mail");
58     shutdown_mail();
59 }
60
61 my $pid = fork();
62 if (! $pid) {
63     syslog ("info", "pl_mom: Launching reboot kicker");
64     reboot_kicker();
65     die (0);
66 }
67 $pid = fork();
68 if (! $pid) {
69     syslog ("info", "pl_mom: Launching bandwidth monitor");
70     bandwidth_monitor();
71     die (0);
72 }
73
74 while (1) {
75     $used = int(swap_used());
76
77     if (defined($old_used)) {
78         if ($used >= $old_used + $change_thresh) {
79             syslog ("info", "pl_mom: %d%% swap consumed in last %d seconds",
80                     $used - $old_used, $sleep);
81         }
82     }
83
84     if ($used >= $log_thresh) {
85         if (! defined($old_used) || $used != $old_used) {
86             syslog ("info", "pl_mom: Swap used: %d%%", $used);
87         }
88         get_slice_info();
89         my $hog = memory_hog();
90         if ($hog) {
91             if ($used < $kill_thresh) {
92                 if (! defined($Warning{$hog})) {
93                     $Warning{$hog} = "sent";
94                     syslog ("warning", "pl_mom: Slice $hog is ".
95                             "using $Slice{$hog}{mem_pct}%% of memory");
96                     #slice_warning_mail($hog);
97                 }
98             } else {
99                 my $id = `id -u $hog`;
100                 chomp($id);
101                 my $top = `chcontext --ctx $id top -b -n 1`;
102                 syslog ("warning", "pl_mom: Resetting slice $hog");
103                 if (! $debug) {
104                     slice_reset($hog);
105                 }
106                 syslog ("warning", "pl_mom: Sending mail to slice $hog");
107                 slice_reset_mail($hog, $top);
108             }
109         }
110     }
111     
112     sleep ($sleep);
113
114     $old_used = $used;
115 }
116
117 sub reboot_kicker {
118     while (1) {
119         $used = swap_used();
120
121         if ($used >= $reboot_thresh) {
122             syslog ("warning", "pl_mom: Rebooting node");
123
124             system("touch $rebootfile");
125             if (! $debug) {
126                 system("shutdown -r now");
127             }
128             die (0);
129         }
130         
131         sleep (1);
132     }
133 }
134
135 sub bandwidth_monitor {
136     while (1) {
137         # See if a new day has started for bandwidth monitoring
138         chomp($now = `date -u +%D`);
139         if (-e $daily_stamp) {
140             chomp($stamp = `cat $daily_stamp`);
141         }
142         if (! defined($stamp) || !($stamp =~ $now)) {
143             open (STAMP, ">$daily_stamp") || 
144                 die "Can't open file $daily_stamp for writing: $!\n";
145             print STAMP "$now\n";
146             close STAMP;
147             unlink ($daily_log);
148
149             # Could save the list of capped slices in a file in order to
150             # avoid re-sending mails if the daemon restarts.
151             # Also may want a list of slices that are exempt from capping.
152             if (defined(%Cap)) {
153                 undef %Cap;
154             }
155
156             # Need to reset bandwidth limits here
157
158             syslog("info", "pl_mom: Beginning bandwidth monitoring for $now");
159         }
160
161         # Get baseline counts
162         `touch $daily_log`;
163         open (BASE, "+<$daily_log") ||
164             print "Cannot open $daily_log; $!\n";
165         while (<BASE>) {
166             my ($sliceid, $bytecount) = split(/ /);
167             $Start{$sliceid} = $bytecount;
168         }
169         
170         $status = `tc -s -d qdisc show`;
171         @lines = split(/\n/, $status);
172         for ($i = 0; $i < @lines; $i++) {
173             if ($lines[$i] =~ /qdisc pfifo/) {
174                 $lines[$i] =~ s/^ +//;
175                 @fields = split(/ /, $lines[$i]);
176                 $slice = $fields[2];
177                 $slice =~ s/://;
178
179                 if ($slice != 9999) {
180                     $lines[$i+1] =~ s/^ +//;
181                     @fields = split(/ /, $lines[$i+1]);
182                     $bytes = $fields[1];
183                     #if ($bytes) {print "Slice $slice sent $bytes bytes\n";}
184                     
185                     if (! defined($Start{$slice})) {
186                         print BASE "$slice $bytes\n";
187                         $Start{$slice} = $bytes;
188                     }
189                     $Now{$slice} = $bytes;
190                 }
191             }
192         }
193         close (BASE);
194
195         foreach $slice ( sort (keys %Start) ) {
196             if (defined $Now{$slice}) {
197                 $today = $Now{$slice} - $Start{$slice};
198                 if ($today >= $byte_cutoff && ! defined($Cap{$slice})) {
199                     $Cap{$slice} = "sent";
200                     $slicename = get_slice_name($slice);
201                     if ($slicename) {
202                         bw_cap_mail($slicename);
203                     } else {
204                         syslog("warning", "pl_mom: Could not find slice name".
205                                " for slice ID $slice");
206                     }
207                     # Add bandwidth cap here
208                 }
209             } else {
210                 # The /proc/virtual/<id> directory is gone...
211             }
212         }
213
214         sleep($bwmon_sleep);
215     }
216 }
217
218 sub send_mail {
219     # Arg 0: recipient addresses, comma-separated string
220     # Arg 1: subject line
221     # Arg 2: body of message
222     my $to = "To: $_[0]\n";
223     my $from = "From: $from_addr\n";
224     my $subject = "Subject: $_[1]\n";
225     my $msg = $_[2];
226
227     open(SENDMAIL, "|$sendmail") or die "Cannot open $sendmail: $!";
228     print SENDMAIL $to;
229     print SENDMAIL $from;
230     print SENDMAIL $subject;
231     print SENDMAIL "Content-type: text/plain\n\n";
232     print SENDMAIL $msg;
233     close(SENDMAIL);
234 }
235
236 sub get_date {
237     my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdat) 
238         = localtime(time);
239     my $date = sprintf("%4d-%02d-%02d %02d:%02d:%02d", 
240                        $year+1900, $mon+1, $mday, $hour, $min, $sec);
241     return $date;
242 }
243
244 sub get_slice_name {
245     # Arg 0: slice ID
246
247     # Need to map slice id to slice name; is there a sensor?
248     # For now, get it from /etc/passwd
249     my $name = "";
250     open (PASSWD, "</etc/passwd") ||
251         print "Cannot open /etc/passwd; $!\n";
252     while (<PASSWD>) {
253         my ($slicename, $passwd, $sliceid) = split(/:/);
254         if ($sliceid == $_[0]) {
255             $name = $slicename;
256         }
257     }
258     close PASSWD;
259     return $name;
260 }
261
262 sub bw_cap_mail {
263     my $hostname = hostname();
264     my $date = get_date();
265     my $sent = int($byte_cutoff/1000000000);
266
267     # Put this here because this is where we have the 
268     syslog("warning", "pl_mom: Capping bandwidth of slice ".
269            "$slicename at $bwcap until midnight GMT.");
270
271     send_mail("acb\@planet-lab.org",
272               "$proc capped bandwidth of slice $slicename on $hostname",
273               "Slice $slicename has transmitted more than ${sent}GB today".
274               " on $hostname.  ".
275               "Its bandwidth will be capped at $bwcap until midnight GMT.".
276               "\n\n$date $hostname bwcap $slicename\n");
277 }
278
279 sub shutdown_mail {
280     my $hostname = hostname(); 
281     my $date = get_date();
282     send_mail($alias_addr, 
283               "$proc rebooted $hostname", 
284               "Swap space was exhausted on $hostname and so $proc rebooted ".
285               "it.\n\nAs of $date, the node has successfully come back ".
286               "online.\n\n$date $hostname reboot\n");
287 }
288
289 sub slice_reset_mail {
290     my $hog = $_[0];
291     my $top = $_[1];
292     my $hog_mem = sprintf ("%0.f", $Slice{$hog}{pmem}/1000);
293     my $hog_pct = $Slice{$hog}{mem_pct};
294     my $hostname = hostname(); 
295     my $date = get_date();
296     send_mail("$alias_addr, $hog\@slices.planet-lab.org",
297               "$proc reset slice $hog on $hostname",
298               "As of $date, swap space is nearly exhausted on $hostname.\n\n".
299               "Slice $hog is being reset since it is the largest consumer ".
300               "of physical memory at ${hog_mem}MB ($hog_pct%).\n\n".
301               "Please reply to this message explaining the nature of your ".
302               "experiment, and what you are doing to address the problem.\n".
303               "\nOutput of 'top -b -n 1' in your slice prior to reset:\n".
304               "$top\n\n$date $hostname reset $hog\n");
305 }
306
307 sub slice_warning_mail {
308     my $hog = $_[0];
309     my $hog_mem = sprintf ("%0.f", $Slice{$hog}{pmem}/1000);
310     my $hog_pct = $Slice{$hog}{mem_pct};
311     my $hostname = hostname(); 
312     my $date = get_date();
313
314     if ($hog =~ /^root$/) {
315         $to = $alias_addr;
316     } else {
317         $to = "$alias_addr, $hog\@slices.planet-lab.org";
318     }   
319
320     send_mail($to,
321               "$proc may reset slice $hog on $hostname",
322               "As of $date, swap space is over $log_thresh% full on ".
323               "$hostname.\n\nSlice $hog is the largest consumer ".
324               "of physical memory at ${hog_mem}MB ($hog_pct%).\n".
325               "Please check the memory usage of your slice to avoid a ".
326               "reset.\n\n$date $hostname warning $hog\n");
327 }
328
329 sub unkillable_alarm_mail {
330     my $hog = $_[0];
331     my $hog_mem = sprintf ("%0.f", $Slice{$hog}{pmem}/1000);
332     my $hog_pct = $Slice{$hog}{mem_pct};
333     my $hostname = hostname(); 
334     my $date = get_date();
335
336     if ($hog =~ /^root$/) {
337         $to = $alias_addr;
338     } else {
339         $to = "$alias_addr, $hog\@slices.planet-lab.org";
340     }
341
342     send_mail($to,
343               "$proc: alarm for slice $hog on $hostname",
344               "As of $date, swap space is over $log_thresh% full on ".
345               "$hostname.\n\nSlice $hog is the largest consumer ".
346               "of physical memory at ${hog_mem}MB ($hog_pct%).\n".
347               "The slice will not be reset, but please verify its behavior.\n".
348               "\n$date $hostname alarm $hog\n");
349 }
350
351 sub slice_reset {
352     my $slice = $_[0];
353     my $sliceid = $Slice{$slice}{ctx};
354     system("chcontext --ctx $sliceid sudo kill -9 -1");
355     system("/etc/init.d/vserver-init start $slice");
356 }
357
358 sub swap_used {
359     open (SWAP, "</proc/swaps") ||
360         die "Cannot open /proc/swaps; $!\n";
361
362     $line = <SWAP>;
363     $line = <SWAP>;
364     $line =~ s/[\t ]+/ /g;
365
366     my ($filename, $type, $size, $used, $priority) = split(/ /, $line);
367     close SWAP;
368  
369     return 100*($used/$size);
370 }
371
372 sub get_slice_info {
373     if (! $debug) {
374         #$content = get "http://127.0.0.1:3100/slicestat";
375         $content = `curl -s http://127.0.0.1:3100/slicestat`;
376     } else {
377         $content = `cat ../pl_mom-deploy/slicestat`
378     }
379     my @lines = split(/\n/, $content);
380     %Slice = ();
381     foreach $line (@lines) {
382         my ($slice, $ctx, $cpu_pct, $mem_pct, $pmem, $vmem, $ntasks) 
383             = split(/,/,$line);
384         $Slice{$slice}{ctx} = $ctx;
385         $Slice{$slice}{cpu_pct} = $cpu_pct;
386         $Slice{$slice}{mem_pct} = $mem_pct;
387         $Slice{$slice}{pmem} = $pmem;
388         $Slice{$slice}{vmem} = $vmem;
389         $Slice{$slice}{ntasks} = $ntasks;
390     }
391 }
392
393 sub memory_hog {
394     @keys = sort { $Slice{$b}{mem_pct} <=> $Slice{$a}{mem_pct} } (keys %Slice);
395     foreach $key (@keys) {
396         if ($Slice{$key}{mem_pct} >= $min_thresh) {
397             if ($key =~ /^root$/ || $key =~ /slicestat/ || $key =~ /netflow/) {
398                 if (! defined ($Warning{$key})) {
399                     $Warning{$key} = "sent";
400                     syslog ("warning", "pl_mom: Sending alarm mail to ".
401                             "unkillable slice $key, using ".
402                             "$Slice{$key}{mem_pct}%% of memory");
403                     unkillable_alarm_mail($key);
404                 }
405             } else {
406                 return $key;
407             }
408         } else {
409             #syslog ("info", "pl_mom: No killable slice using > ".
410             #    "$min_thresh%% memory");
411             return;
412         }
413     }
414 }
415
416 sub daemonize {
417     chdir '/'                 or die "Can't chdir to /: $!";
418     open STDIN, '/dev/null'   or die "Can't read /dev/null: $!";
419     open STDOUT, '>>/dev/null' or die "Can't write to /dev/null: $!";
420     open STDERR, '>>/dev/null' or die "Can't write to /dev/null: $!";
421     defined(my $pid = fork)   or die "Can't fork: $!";
422     exit if $pid;
423     setsid                    or die "Can't start a new session: $!";
424     umask 0;
425 }