|
1 | 1 | #!/usr/bin/env perl |
2 | | -use Data::Printer; |
3 | 2 | use DBI; |
| 3 | +use Fcntl qw(:flock); |
4 | 4 | use HTTP::Request::Common qw(GET DELETE); |
5 | 5 | use JSON::XS; |
6 | 6 | use LWP::UserAgent; |
7 | 7 | use constant URL => q{https://rdap.org/stats}; |
8 | 8 | use vars qw(@SERIES $DB); |
9 | 9 | use common::sense; |
10 | 10 |
|
| 11 | +if (!flock(DATA, LOCK_EX | LOCK_NB)) { |
| 12 | + say STDERR q{waiting for existing process to finish...}; |
| 13 | + flock(DATA, LOCK_EX); |
| 14 | +} |
| 15 | + |
11 | 16 | @SERIES = qw(status type user_agent network); |
12 | 17 |
|
| 18 | +say STDERR q{opening database connection...}; |
13 | 19 | my $DB = DBI->connect(sprintf( |
14 | 20 | q{dbi:SQLite:dbname=%s}, |
15 | 21 | $ARGV[0] || q{./stats.db} |
16 | 22 | )); |
17 | 23 |
|
18 | 24 | $DB->do(q{CREATE TABLE IF NOT EXISTS total_queries ( |
19 | 25 | id INTEGER PRIMARY KEY, |
20 | | - timestamp INTEGER, |
| 26 | + timestamp INTEGER UNIQUE, |
21 | 27 | count INTEGER |
22 | 28 | )}); |
23 | 29 |
|
|
28 | 34 | `%s` TEXT, |
29 | 35 | `count` INTEGER |
30 | 36 | )}, $column, $column)); |
| 37 | + |
| 38 | + $DB->do(sprintf( |
| 39 | + q{CREATE UNIQUE INDEX IF NOT EXISTS `queries_by_%s_index` ON `queries_by_%s`(`timestamp`, `%s`)}, |
| 40 | + $column, |
| 41 | + $column, |
| 42 | + $column, |
| 43 | + )); |
31 | 44 | } |
32 | 45 |
|
33 | 46 | my $ua = LWP::UserAgent->new; |
|
38 | 51 |
|
39 | 52 | my $req1 = GET(URL); |
40 | 53 | $req1->header(authorization => sprintf(q{Bearer %s}, $ENV{STATS_TOKEN})); |
| 54 | + |
| 55 | +say STDERR q{getting stats...}; |
| 56 | + |
41 | 57 | my $res1 = $ua->request($req1); |
42 | 58 |
|
43 | 59 | die($res1->status_line) unless ($res1->is_success); |
|
48 | 64 | my $req2 = DELETE(URL); |
49 | 65 | $req2->header(authorization => sprintf(q{Bearer %s}, $ENV{STATS_TOKEN})); |
50 | 66 |
|
| 67 | +say STDERR q{purging stats...}; |
51 | 68 | my $res2 = $ua->request($req2); |
52 | 69 |
|
53 | 70 | die($res2->status_line) unless ($res2->is_success); |
|
60 | 77 |
|
61 | 78 | my $timestamp = delete($stats->{timestamp}); |
62 | 79 |
|
| 80 | +say STDERR q{updating database...}; |
| 81 | + |
63 | 82 | $DB->prepare(q{ |
64 | 83 | INSERT INTO `total_queries` |
65 | 84 | (`timestamp`, `count`) |
|
90 | 109 | ); |
91 | 110 | } |
92 | 111 | } |
| 112 | + |
| 113 | +say STDERR q{done}; |
| 114 | + |
| 115 | +__DATA__ |
0 commit comments