-
Notifications
You must be signed in to change notification settings - Fork 3
/
anemoeater
executable file
·382 lines (323 loc) · 12.5 KB
/
anemoeater
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
#!/usr/bin/perl
########################################################################
# Copyright (C) 2016, 2020 yoku0825
# Copyright (C) 2018, yokogawa-k
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
########################################################################
use constant VERSION => "0.0.6";
use strict;
use warnings;
use utf8;
use FindBin qw/$Bin/;
use Time::Piece;
use File::Basename qw/basename/;
use DBI;
use Parallel::ForkManager;
use Socket;
use Getopt::Long qw/:config posix_default bundling no_ignore_case gnu_compat/;
use constant TIME_FORMAT => ["%Y/%m/%d %H:%M:%S",
"%Y/%m/%d %H:%M",
"%Y/%m/%d",
"%Y-%m-%d %H:%M:%S",
"%Y-%m-%d %H:%M",
"%Y-%m-%d",
"%Y%m%d%H%M%S",
"%Y%m%d%H%M",
"%Y%m%d"];
our $hostname= $ENV{HOSTNAME} ? $ENV{HOSTNAME} : "localhost";
our $ipaddr = inet_ntoa(inet_aton($hostname));
my $opt= {parallel => int(&count_cpu_thread * 1.5),
since => Time::Piece::localtime->add_months(-1)->strftime("%Y%m%d"),
until => "9999/12/31",
type => "slowlog",
report => 15,
cell => 5,
help => 0,
docker => 1,
local => 0,
pt_docker => 1,
};
GetOptions($opt, qw/socket=s host=s port=i user=s password=s
parallel=i since=s until=s type=s report=i cell=i
help usage no-docker local use-docker-for-pt
pt-query-digest=s /) or die;
usage() if $opt->{help} || $opt->{usage};
usage("--cell should not be 0") unless $opt->{cell};
my $since= parse_time($opt->{since}, &TIME_FORMAT);
usage("Can't parse --since") unless $since;
my $until= parse_time($opt->{until}, &TIME_FORMAT);
usage("Can't parse --until") unless $until;
usage("'$opt->{type}' is not a valid input type") unless grep {$_ eq $opt->{type}} qw(slowlog binlog tcpdump);
$opt->{docker}= 0 if $opt->{"no-docker"};
$opt->{pt_docker}= 1 if $opt->{"use-docker-for-pt"};
$opt->{"pt-query-digest"} //= "/usr/bin/pt-query-digest";
our $pt_qd;
if ($opt->{pt_docker})
{
system("sudo docker pull yoku0825/percona-toolkit > /dev/null");
$pt_qd= "sudo docker run --rm -i yoku0825/percona-toolkit pt-query-digest";
}
else
{
usage(sprintf("%s isn't executable.\n" .
"Use --use-docker-for-pt or --pt-query-digest=/path/to/pt-query-digest for using pt-query-digest.",
$opt->{"pt-query-digest"})) unless -x $opt->{"pt-query-digest"};
$pt_qd= $opt->{"pt-query-digest"};
}
### Anemometer is broken in pt-query-digest >= 3.0.11
### See https://github.com/box/Anemometer/issues/200
my $pt_version= `$pt_qd --version`;
$pt_version =~ /pt-query-digest\s+(\d+)\.(\d+)\.(\d+)/;
if ($1 * 10000 + $2 * 100 + $3 >= 30011)
{
die("box/Anemometer is broken in pt-query-digest >= 3.0.11.\n" .
"See https://github.com/box/Anemometer/issues/200");
}
my @files= @ARGV;
usage("Slow log file was not specified.") unless @files;
foreach my $file (@files)
{
usage("Slow log $file can't read.") unless -r $file;
}
### Starting docker container.
if ($opt->{docker})
{
my $repository;
if ($opt->{local})
{
$repository= "anemoeater";
system("sudo docker build -t anemoeater -f $Bin/Dockerfile/Anemometer-Server .");
}
else
{
system("sudo docker pull yoku0825/anemoeater > /dev/null");
$repository= "yoku0825/anemoeater";
}
my $container_id= `sudo docker run -d -P $repository`;
chomp($container_id);
my $container_ipaddr= `sudo docker inspect -f '{{.NetworkSettings.IPAddress}}' $container_id`;
chomp($container_ipaddr);
my $publish_port= `sudo docker inspect $container_id | awk '/HostPort/{print \$2}' | tr -d \\"`;
chomp($publish_port);
### wait container's mysqld starts to run
my $max_retry= 10;
my $retry= 0;
while ()
{
eval
{
my $conn= DBI->connect("dbi:mysql:;host=$container_ipaddr", "anemometer", "",
{RaiseError => 1, PrintError => 0});
$conn->do("SELECT CURRENT_USER()");
};
last unless $@;
if (++$retry > $max_retry)
{
die("Attempt to connect to container $container_id, " .
"but can't connect $retry times and giving up to run.\n" .
"Please check 'docker logs $container_id' and confirm container runs correctly or not.");
}
else
{
sleep 3;
}
}
$opt->{host} = $container_ipaddr;
$opt->{user} = "anemometer";
$opt->{password}= undef;
$opt->{port} = undef;
printf("Docker container starts with %s.\n", $container_ipaddr);
printf("URL will be http://%s:%d/anemometer\n", $ipaddr, $publish_port);
}
my $pt_dsn= "D=slow_query_log";
$pt_dsn .= sprintf(",h=%s", $opt->{host}) if $opt->{host};
$pt_dsn .= sprintf(",P=%d", $opt->{port}) if $opt->{port};
$pt_dsn .= sprintf(",u=%s", $opt->{user}) if $opt->{user};
$pt_dsn .= sprintf(",p=%s", $opt->{password}) if $opt->{password};
my $cmd_format= q{| %s --type=%s --no-version-check --review %s --history %s --no-report --limit=0%% --filter='$event->{Bytes} = length($event->{arg}) and $event->{hostname}="%s" and ($event->{db} || "") !~ /^(information_schema|performance_schema|sys)$/i and (($event->{fingerprint} || "") !~ /\s`?(information_schema|performance_schema|sys)`?\./i)' > /dev/null};
my $pm = Parallel::ForkManager->new($opt->{parallel});
foreach my $file (@files)
{
my $in;
if ($opt->{type} eq "binlog")
{
### decode by mysqlbinlog
open($in, "mysqlbinlog $file |");
}
else
{
### open as slow-log.
open($in, "<", $file);
}
my $event = 0;
my $timetmp= 0;
my $current_time;
my $previous_time;
my @buffer = ();
while (<$in>)
{
### Slowlog or Binlog style.
if (/^# Time: (?<timestr>.+)$/ || /^#(?<timestr>[\d\s:]+) server id/)
{
if ($+{timestr} =~ /(?<year>\d{2})(?<month>\d{2})(?<day>\d{2})\s+
(?<hour>\d{1,2}):(?<minute>\d{2}):(?<second>\d{2})/x)
{
### 5.0, 5.1, 5.5, 5.6 style slow-log and binary-log.
# "# Time: %02d%02d%02d %2d:%02d:%02d\n",
### normalize without seconds.
$timetmp= sprintf("20%02d%02d%02d%02d%02d",
$+{year}, $+{month}, $+{day},
$+{hour}, $+{minute});
}
elsif ($+{timestr} =~ /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})T
(?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2})\.
(?<fraction>\d{6})(?<timezone>.*)/x)
{
### 5.7 style.
# "# Time: %04d-%02d-%02dT%02d:%02d:%02d.%06lu%s",
### normalize without seconds.
$timetmp= sprintf("%04d%02d%02d%02d%02d",
$+{year}, $+{month}, $+{day},
$+{hour}, $+{minute});
### replace buffer's timestr.
$_= sprintf("# Time: %02d%02d%02d %2d:%02d:%02d\n",
substr($+{year}, 2, 2), $+{month}, $+{day},
$+{hour}, $+{minute}, $+{second});
}
else
{
### Unknown format.
$timetmp= 0;
}
$current_time= Time::Piece->strptime($timetmp, "%Y%m%d%H%M%S");
if (!($previous_time) || ($current_time - $previous_time) >= ($opt->{cell} * 60))
{
$event= &send_pt_qd($current_time, $event, $file, @buffer);
$previous_time= $current_time;
@buffer= ();
}
}
### tcpdump
elsif ($opt->{type} eq "tcpdump")
{
if (/^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})\s
(?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2})\.(?<fraction>\d{6})\s
IP\s[0-9\.]+\s[<>]\s[0-9\.]+:\stcp\s[0-9]+$/x)
{
### normalize without seconds.
$timetmp= sprintf("%04d%02d%02d%02d%02d",
$+{year}, $+{month}, $+{day},
$+{hour}, $+{minute});
$current_time= Time::Piece->strptime($timetmp, "%Y%m%d%H%M%S");
if (!($previous_time) || ($current_time - $previous_time) >= ($opt->{cell} * 60))
{
$event= &send_pt_qd($current_time, $event, $file, @buffer);
$previous_time= $current_time;
@buffer= ();
}
}
}
push(@buffer, $_);
}
### flush last block.
&send_pt_qd($current_time, $event, $file, @buffer) if @buffer;
$pm->wait_all_children;
### Update hostname_max by filename.
my $dsn = "dbi:mysql:slow_query_log";
$dsn .= sprintf(";host=%s", $opt->{host}) if $opt->{host};
$dsn .= sprintf(";port=%d", $opt->{port}) if $opt->{port};
my $user = $opt->{user} ? $opt->{user} : "anemometer";
my $password= $opt->{password} ? $opt->{password} : "";
my $conn= DBI->connect($dsn, $user, $password, {mysql_use_utf8 => 1});
$conn->do("UPDATE global_query_review_history SET hostname_max= REPLACE(?, '.log', '') WHERE hostname_max= ?",
undef,
basename($file), $hostname);
}
exit 0;
sub usage
{
my ($msg)= @_;
print $msg, "\n" if $msg;
print << "EOF";
$0 [--user=s] [--password=s] [--port=i] [--host=s] [--socket=s]
[--parallel=i] [--since=i] [--until=i] [--report=i] [--type=s] slowlog
$0 is split slowlog and process by pt-query-digest.
--socket=s MySQL socket which pt-query-digest uses to connection.
--host=s MySQL host which pt-query-digest uses to connection.
--port=i MySQL port which pt-query-digest uses to connection.
--user=s MySQL user which pt-query-digest uses to connection.
--password=s MySQL password which pt-query-digest uses to connection.
--parallel=i How many processes does script run concurrently (default: CPU threads * 1.5)
--since=i Filter for processing slow-log, see also "Supported datetime styles".
--until=i Filter for processing slow-log, see also "Supported datetime styles".
--type The type of input to parse (default: slowlog). The permitted types are slowlog, binlog, tcpdump.
--report=i Print message each processed events n times (default: 15)
--cell=i How many minutes buffering and aggregating (default: 5[min])
--no-docker Do not use docker image. Must specify --user, --password, --port and --host(or --socket).
--local Using docker container but using local built(Do not use yoku0825/anemoeater)
--use-docker-for-pt Using pt-query-digest via docker contaier (yoku0825/percona-toolkit)
Supported datetime styles are
"%Y/%m/%d %H:%M:%S" (ex. "2016/02/08 11:01:22")
"%Y/%m/%d %H:%M" (ex. "2016/02/08 11:01")
"%Y/%m/%d" (ex. "2016/02/08")
"%Y-%m-%d %H:%M:%S" (ex. "2016-02-08 11:01:22")
"%Y-%m-%d %H:%M" (ex. "2016-02-08 11:01")
"%Y-%m-%d" (ex. "2016-02-08")
"%Y%m%d%H%M%S" (ex. "20160208110122")
"%Y%m%d%H%M" (ex. "201602081101")
"%Y%m%d" (ex. "20160208")
EOF
exit 0;
}
sub parse_time
{
my ($timestr, $candidate)= @_;
my $ret;
foreach (@$candidate)
{
eval
{
$ret= Time::Piece->strptime($timestr, $_);
};
return $ret unless $@;
}
}
sub send_pt_qd
{
my ($current_time, $event, $file, @buffer)= @_;
return 0 unless ($since <= $current_time && $current_time <= $until);
printf("processing %s %s at %s.\n", $current_time->ymd, $current_time->hms, basename($file))
if ($opt->{report} && (++$event % $opt->{report}) == 0);
unless ($pm->start)
{
open(my $process, sprintf($cmd_format,
$pt_qd,
$opt->{type},
$pt_dsn . ",t=global_query_review",
$pt_dsn . ",t=global_query_review_history",
$hostname));
print $process @buffer;
close($process);
$pm->finish;
}
return ++$event;
}
sub count_cpu_thread
{
my $thread= `grep processor /proc/cpuinfo | tail -1 | awk '{print \$3}'`;
chomp($thread);
return $thread ? $thread : 1;
}