DBConnection.pm 9.28 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
=pod 

=head1 NAME

    Bio::EnsEMBL::Hive::DBSQL::DBConnection

=head1 SYNOPSIS

    my $url = $dbc->url();

=head1 DESCRIPTION

13
    Extends the functionality of Bio::EnsEMBL::Hive::DBSQL::CoreDBConnection with things needed by the Hive
14

15
16
=head1 LICENSE

17
    Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
18
19
20
21
22
23
24
25
26
27

    Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software distributed under the License
    is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and limitations under the License.

28
29
=head1 CONTACT

30
    Please subscribe to the Hive mailing list:  http://listserver.ebi.ac.uk/mailman/listinfo/ehive-users  to discuss Hive-related questions or to be notified of our updates
31
32
33

=cut

34

35
36
37
38
39
package Bio::EnsEMBL::Hive::DBSQL::DBConnection;

use strict;
use warnings;

40
use Time::HiRes ('usleep');
41
42
use Bio::EnsEMBL::Hive::Utils::URL;

43
use base ('Bio::EnsEMBL::Hive::DBSQL::CoreDBConnection');
44
45


46
47
sub new {
    my $class = shift;
48
    my %flags = @_;
49

50
    if(my $url = delete $flags{'-url'}) {
51
52
53
        if(my $parsed_url = Bio::EnsEMBL::Hive::Utils::URL::parse( $url )) {

            return $class->SUPER::new(
54
55
56
57
58
                %flags,     # they act as overridable defaults

                ( map { ("-$_" => $parsed_url->{$_}) } ( 'driver', 'host', 'port', 'user', 'pass', 'dbname' ) ),    # parentheses are essential

                ( map { ("-$_" => $parsed_url->{'conn_params'}->{$_}) } keys %{$parsed_url->{'conn_params'}}  ),    # parentheses are essential
59
60
61
62
63
64
65
66
67
68
            );

        } else {
            die "Could not create DBC because could not parse the URL '$url'";
        }
    } else {
        return $class->SUPER::new( @_ );
    }
}

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
=head2 url

    Arg [1]    : String $environment_variable_name_to_store_password_in (optional)
    Example    : $url = $dbc->url;
    Description: Constructs a URL string for this database connection.
    Returntype : string of format  mysql://<user>:<pass>@<host>:<port>/<dbname>
                               or  sqlite:///<dbname>
    Exceptions : none
    Caller     : general

=cut

sub url {
    my ($self, $psw_env_var_name) = @_;

    my $url = $self->driver . '://';

    if($self->username) {
        $url .= $self->username;

        if(my $psw_expression = $self->password) {
            if($psw_env_var_name) {
                $ENV{$psw_env_var_name} = $psw_expression;
                $psw_expression = '${'.$psw_env_var_name.'}';
            }
            $url .= ':'.$psw_expression if($psw_expression);
        }

        $url .= '@';
    }

    if($self->host) {
        $url .= $self->host;

        if($self->port) {
            $url .= ':'.$self->port;
        }
    }
    $url .= '/' . $self->dbname;

109
110
111
112
113
114
115
116
    my @opt_pairs = ();
    foreach my $option ('disconnect_when_inactive', 'wait_timeout', 'reconnect_when_lost') {
        if( defined(my $value = $self->$option()) ) {
            push @opt_pairs, "$option=$value";
        }
    }
    $url = join(';', $url, @opt_pairs);

117
118
119
120
    return $url;
}


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
sub connect {       # a wrapper that imitates CSMA/CD protocol's incremental backoff-and-retry approach
    my $self        = shift @_;

    my $attempts    = 8;
    my $sleep_sec   = 1;
    my $retval;

    foreach my $attempt (1..$attempts) {
        eval {
            $retval = $self->SUPER::connect( @_ );
            1;
        } or do {
            if( ($@ =~ /Could not connect to database.+?failed: Too many connections/s)                             # problem on server side (configured with not enough connections)
             or ($@ =~ /Could not connect to database.+?failed: Can't connect to \w+? server on '.+?' \(99\)/s)     # problem on client side (cooling down period after a disconnect)
            ) {

                warn "Possibly transient problem conecting to the database (attempt #$attempt). Will try again in $sleep_sec sec";

                usleep( $sleep_sec*1000000 );
                $sleep_sec *= 2;
                next;

            } else {     # but definitely report other errors

                die $@;
            }
        };
        last;   # stop looping once we succeeded
    }

    if($@) {
        die "After $attempts attempts still could not connect() : $@";
    }

    return $retval;
}


sub protected_prepare_execute {     # try to resolve certain mysql "Deadlocks" by imitating CSMA/CD protocol's incremental backoff-and-retry approach (a useful workaround even in mysql 5.1.61)
Leo Gordon's avatar
Leo Gordon committed
160
161
162
    my $self                    = shift @_;
    my $sql_params              = shift @_;
    my $deadlock_log_callback   = shift @_;
163

164
    my $sql_cmd         = shift @$sql_params;
165

166
    my $attempts        = 9;
167
    my $sleep_max_sec   = 1;
168

Leo Gordon's avatar
Leo Gordon committed
169
    my $retval;
170
    my $query_msg;
Leo Gordon's avatar
Leo Gordon committed
171

172
    foreach my $attempt (1..$attempts) {
173
        eval {
174
175
            my $sth = $self->prepare( $sql_cmd );
            $retval = $sth->execute( @$sql_params );
176
177
178
            $sth->finish;
            1;
        } or do {
179
            $query_msg = "QUERY: $sql_cmd, PARAMS: (".join(', ',@$sql_params).")";
180

181
            if( $@ =~ /Deadlock found when trying to get lock; try restarting transaction/ ) {
Leo Gordon's avatar
Leo Gordon committed
182

183
184
                my $this_sleep_sec = int( rand( $sleep_max_sec )*100 ) / 100.0;

185
186
                if( $deadlock_log_callback ) {
                    $deadlock_log_callback->( " temporarily failed due to a DEADLOCK in the database (attempt #$attempt). Will try again in $this_sleep_sec sec" );
Leo Gordon's avatar
Leo Gordon committed
187
                }
188
189
190

                usleep( $this_sleep_sec*1000000 );
                $sleep_max_sec *= 2;
191
                next;
192
193
194
195

            } else {     # but definitely report other errors

                die "$@ -- $query_msg";
196
197
            }
        };
198
        last;   # stop looping once we succeeded
199
    }
200
201

    die "After $attempts attempts the query $query_msg still cannot be run: $@" if($@);
Leo Gordon's avatar
Leo Gordon committed
202
203

    return $retval;
204
205
}

206
207
208
209
210
211
212
213
214
215
216
217
218
our $pass_internal_counter = 0;
sub to_cmd {
    my ($self, $executable, $prepend, $append, $sqlcmd, $hide_password_in_env) = @_;

    my $driver = $self->driver || 'mysql';

    my $dbname = $self->dbname;
    if($sqlcmd) {
        if($sqlcmd =~ /(DROP\s+DATABASE(?:\s+IF\s+EXISTS)?\s*?)(?:\s+(\w+))?/i) {
            $dbname = $2 if $2;

            if($driver eq 'sqlite') {
                return ['rm', '-f', $dbname];
219
220
221
222
223
            } else {
                if (not $dbname) {
                    die "'DROP DATABASE' needs a database name\n";
                }
                $sqlcmd = "$1 $dbname" unless $2;
224
225
226
227
228
229
230
                $dbname = '';
            }
        } elsif($sqlcmd =~ /(CREATE\s+DATABASE\s*?)(?:\s+(\w+))?/i ) {
            $dbname = $2 if $2;

            if($driver eq 'sqlite') {
                return ['touch', $dbname];
231
232
233
234
            } else {
                if (not $dbname) {
                    die "'CREATE DATABASE' needs a database name\n";
                }
235
236
237
238
                my %limits = ( 'mysql' => 64, 'pgsql' => 63 );
                if (length($dbname) > $limits{$driver}) {
                    die "Database name '$dbname' is too long (> $limits{$driver}). Cannot create the database\n";
                }
239
                $sqlcmd = "$1 $dbname" unless $2;
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
                $dbname = '';
            }
        }
    }

    my @cmd;

    my $hidden_password;
    if ($self->password) {
        if ($hide_password_in_env) {
            my $pass_variable = "EHIVE_TMP_PASSWORD_${pass_internal_counter}";
            $pass_internal_counter++;
            $ENV{$pass_variable} = $self->password;
            $hidden_password = '$'.$pass_variable;
        } else {
            $hidden_password = $self->password;
        }
    }

    if($driver eq 'mysql') {
        $executable ||= 'mysql';

        push @cmd, $executable;
        push @cmd, @$prepend                if ($prepend && @$prepend);
        push @cmd, '-h'.$self->host         if $self->host;
        push @cmd, '-P'.$self->port         if $self->port;
        push @cmd, '-u'.$self->username     if $self->username;
        push @cmd, '-p'.$hidden_password    if $self->password;
        push @cmd, ('-e', $sqlcmd)          if $sqlcmd;
        push @cmd, $dbname                  if $dbname;

    } elsif($driver eq 'pgsql') {
        $executable ||= 'psql';

        push @cmd, ('env', 'PGPASSWORD='.$hidden_password)  if ($self->password);
        push @cmd, $executable;
        push @cmd, @$prepend                if ($prepend && @$prepend);
        push @cmd, ('-h', $self->host)      if defined($self->host);
        push @cmd, ('-p', $self->port)      if defined($self->port);
        push @cmd, ('-U', $self->username)  if defined($self->username);
        push @cmd, ('-c', $sqlcmd)          if $sqlcmd;
        push @cmd, $dbname                  if $dbname;

    } elsif($driver eq 'sqlite') {
        $executable ||= 'sqlite3';

        die "sqlite requires a database (file) name\n" unless $dbname;

        push @cmd, $executable;
        push @cmd, @$prepend                if ($prepend && @$prepend);
        push @cmd, $dbname;
        push @cmd, $sqlcmd                  if $sqlcmd;
    }

294
295
    push @cmd, @$append                 if ($append && @$append);

296
297
    return \@cmd;
}
298
299
1;