ensembl-hive  2.8.1
kill_process_by_db.pl
Go to the documentation of this file.
1 #!/usr/bin/env perl
2 # See the NOTICE file distributed with this work for additional information
3 # regarding copyright ownership.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 
17 # kill processes by db pattern
18 
19 use strict;
20 use warnings;
21 
22 use DBI;
23 
24 use Getopt::Long;
25 
26 my ( $host, $user, $pass, $port, $dbpattern );
27 
28 GetOptions( "host|h=s", \$host,
29  "user|u=s", \$user,
30  "pass|p=s", \$pass,
31  "port|P=i", \$port,
32  "dbpattern|pattern=s", \$dbpattern,
33  );
34 
35 if( !$host || !$user || !$pass || !$dbpattern ) {
36  usage();
37 }
38 
39 my $dsn = "DBI:mysql:host=$host";
40 if( $port ) {
41  $dsn .= ";port=$port";
42 }
43 
44 my $db = DBI->connect( $dsn, $user, $pass );
45 
46 my $sth=$db->prepare("SHOW FULL PROCESSLIST") || die $DBI::err.": ".$DBI::errstr;
47 
48 $sth->execute || die DBI::err.": ".$DBI::errstr;
49 
50 my $ref;
51 
52 print "Id \t User \t Host \t db \t Command \t Time \t State \t Info\n";
53 my @proc_ids;
54 
55 while ( $ref = $sth->fetchrow_hashref() ) {
56  if ( $$ref{'db'} =~ /$dbpattern/ ) {
57  push (@proc_ids, $$ref{'Id'});
58  print "$$ref{'Id'} \t $$ref{'Host'} \t $$ref{'db'} \t $$ref{'Command'} \t $$ref{'Time'} \t $$ref{'State'} \t $$ref{'Info'}\n";
59  }
60 }
61 
62 my $proc_id_count = @proc_ids;
63 if ($proc_id_count > 0) {
64  print "Are you sure you want to kill process(es) listed above? (y/n)\n";
65 } else {
66  print "No processes found for db pattern $dbpattern\n";
67 }
68 my $decision = <>;
69 
70 if ($decision == 'y') {
71  my $killed_count = 0;
72  foreach my $proc_id (@proc_ids) {
73  if ( $db->do("KILL $proc_id") ) {
74  $killed_count ++;
75  } else { print $DBI::errstr; }
76  }
77 
78  print "$killed_count procesess were killed\n";
79 
80 }
81 
82 
83 sub usage {
84  print STDERR <<EOF
85 
86  Usage: kill_process_by_db options
87  Where options are: -host hostname
88  -user username
89  -pass password
90  -port port_of_server optional
91  -dbpattern regular expression that the database name has to match
92 EOF
93 ;
94  exit;
95 }
96 
usage
public usage()