DBConnection.pm 9.65 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
Brandon Walts's avatar
Brandon Walts committed
18
    Copyright [2016-2020] EMBL-European Bioinformatics Institute
19 20 21 22 23 24 25 26 27 28

    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.

29 30
=head1 CONTACT

31
    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
32 33 34

=cut

35

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

use strict;
use warnings;

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

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


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

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

            return $class->SUPER::new(
55 56 57 58 59
                %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
60 61 62 63 64 65 66 67 68 69
            );

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

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
=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;

110 111 112 113 114 115 116 117
    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);

118 119 120 121
    return $url;
}


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
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
161 162 163
    my $self                    = shift @_;
    my $sql_params              = shift @_;
    my $deadlock_log_callback   = shift @_;
164

165
    my $sql_cmd         = shift @$sql_params;
166

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

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

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

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

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

186 187
                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
188
                }
189 190 191

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

            } else {     # but definitely report other errors

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

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

    return $retval;
205 206
}

207 208 209 210 211 212 213 214 215 216 217 218 219
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];
220 221 222 223
            } else {
                if (not $dbname) {
                    die "'DROP DATABASE' needs a database name\n";
                }
224 225 226 227 228
                if ($driver eq 'mysql') {
                    $sqlcmd = "$1 \`$dbname\`" unless $2;
                } else {
                    $sqlcmd = "$1 $dbname" unless $2;
                }
229 230
                $dbname = '';
            }
231
        } elsif($sqlcmd =~ /(CREATE\s+DATABASE(?:\s+IF\s+NOT\s+EXISTS)?\s*?)(?:\s+(\w+))?/i ) {
232 233 234 235
            $dbname = $2 if $2;

            if($driver eq 'sqlite') {
                return ['touch', $dbname];
236 237 238 239
            } else {
                if (not $dbname) {
                    die "'CREATE DATABASE' needs a database name\n";
                }
240 241 242 243
                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";
                }
244 245 246 247 248
                if ($driver eq 'mysql') {
                    $sqlcmd = "$1 \`$dbname\`" unless $2;
                } else {
                    $sqlcmd = "$1 $dbname" unless $2;
                }
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
                $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;
    }

303 304
    push @cmd, @$append                 if ($append && @$append);

305 306
    return \@cmd;
}
307 308
1;