App-ElasticSearch-Utilities

 view release on metacpan or  search on metacpan

lib/App/ElasticSearch/Utilities/Connection.pm  view on Meta::CPAN

);


has 'version' => (
    is => 'lazy',
    isa => Str,
    init_arg => undef,
);

sub _build_version {
    my $self = shift;

    # Retry with TLS and/or Auth
    my $resp = $self->request('/',{skip_version_check => 1});
    my $err;
    if( $resp->is_success ) {
        my $ver;
        eval {
            $ver = $resp->content->{version};
        };
        if( $ver ) {
            if( $ver->{distribution} and $ver->{distribution} eq 'opensearch' ) {
                return sprintf "%0.1f", version->parse($ver->{minimum_wire_compatibility_version});
            }
            else {
                return sprintf "%0.1f", version->parse($ver->{number});
            }
        } else {
            $err = "Parsing version failed";
        }
    }
    elsif( $resp->code == 500 && $resp->message eq "Server closed connection without sending any data back" ) {
        $err = "Attempting promotion to HTTPS, try setting 'proto: https' in ~/.es-utils.yaml";
    }
    elsif( $resp->code == 401 ) {
        $err = $self->password ? sprintf("Authorization failed for user '%s'", $self->username)
                               : "Authorization required, try setting 'password-exec: /home/user/bin/get-password.sh` in ~/.es-utils.yaml'";
    }
    else {
        $err = "Failed getting version";
    }
    output({color=>'red',stderr=>1}, sprintf "FAIL [%d] Unable to determine Elasticsearch version: %s", $resp->code, $err);
    output({color=>'red',stderr=>1}, ref $resp->content ? YAML::XS::Dump($resp->content) : $resp->content) if $resp->content;
    exit 1;
}


has 'ua' => (
    is  => 'lazy',
    isa => InstanceOf["LWP::UserAgent"],
);

sub _build_ua {
    my ($self) = @_;

    # Construct the UA Object
    ## no critic
    my $local_version = eval '$VERSION' || '999.9';
    ## use critic
    my $ua = LWP::UserAgent->new(
        keep_alive        => 3,
        agent             => sprintf("%s/%s (Perl %s)", __PACKAGE__, $local_version, $^V),
        protocols_allowed => [qw(http https)],
        timeout           => $self->timeout,
        ssl_opts          => $self->ssl_opts,
    );
    debug({color=>'cyan'}, sprintf "Initialized a UA: %s%s", $ua->agent, $self->password ? ' (password provided)' : '');

    # Decode the JSON Automatically
    $ua->add_handler( response_done => sub {
        my ($response,$lwp_ua,$headers) = @_;
        debug( {color=>'magenta'}, "respone_done handler, got:");
        debug($response->as_string);

        my $ctype = $response->content_type() || 'invalid';
        # JSON Transform
        if( $ctype =~ m{^application/json\b} ) {
            debug({color=>'yellow',indent=>1},"JSON Decoding Response Content");
            eval {
                my $decoded = decode_json( $response->content );
                $response->content($decoded);
            };
        }
        elsif ( $response->is_success && $ctype =~ m{^text/plain} ) {
            # Plain text transform for the _cat API
            debug({color=>'yellow',indent=>1},"Plain Text Transform Response Content");
            my $decoded = [
                grep { defined && length && !/^\s+$/ }
                split /\r?\n/, $response->content
            ];
            debug_var($decoded);
            $response->content($decoded);
        }
        if( my $content = $response->content ) {
            debug({color=>'yellow'}, "After translation:");
            if( is_ref($content) ) {
                debug_var( $content );
            }
            else{
                debug( $content );
            }
        }
        $_[0] = $response;
    });

    # Warn About Basic Auth without TLS
    warn "HTTP Basic Authorization configured and not using TLS, this is not supported"
        if length $self->password && $self->proto ne 'https';

    return $ua;
}


sub request {
    my ($self,$url,$options,$body) = @_;

    # Skip Version Check
    my $skip_version_check = delete $options->{skip_version_check};

    # Build the Path
    $options->{command} ||= $url;



( run in 2.151 seconds using v1.01-cache-2.11-cpan-14f38c9f855 )