?
Current Path : /opt/PUC/lib/PUC/Collector/ |
Linux gator3171.hostgator.com 4.19.286-203.ELK.el7.x86_64 #1 SMP Wed Jun 14 04:33:55 CDT 2023 x86_64 |
Current File : //opt/PUC/lib/PUC/Collector/DataStore.pm |
package PUC::Collector::DataStore; use 5.010_001; use strict; use warnings; use Carp; use HTTP::Tiny; use JSON; use URI; use Log::Log4perl; Log::Log4perl->init_once('/opt/PUC/log4perl.conf'); my $log = Log::Log4perl->get_logger(); ## no critic (ConstantPragma) use constant SWAGGER_WEBAPP_KEYS => qw( domain server username webApp ); use constant SWAGGER_REQUIRED_PARAMS => { domain => [ qw(name type), ], server => [ qw(hostname), ], webApp => [ qw(name), ], }; use constant INTERNAL_EXCEPTION => 599; sub new { my $class = shift; my %args = @_; my $self = { api_key => '', key_file => $args{key_file} // undef, ua => undef, base_url => $args{base_url} || "dryrun://localhost", debug => $args{debug} || 0, }; if ( -f $self->{key_file} ) { open my $secrets_file, '<', $self->{key_file} or croak "DataStore API key not accessible from file (" . $self->{key_file} . "): $!"; $self->{api_key} = <$secrets_file>; # file has only one line with the APIkey-value only close $secrets_file; if ( !$self->{api_key} ) { $log->error ("Failed to read api key! . $self->{key_file}", action => "PUC::Collector::DataStore->new"); print STDERR "Failed to read api key! (" . $self->{key_file} . ")\n"; return ''; } chomp( $self->{api_key} ); } $self->{ua} = HTTP::Tiny->new( timeout => 10, ); return bless( $self, $class ); }; ## no critic (BracedFileHandle CheckedSyscalls) sub send_data { my ( $self, $path, $data ) = @_; my $url = URI->new( $self->{base_url} ); $url->path($path); $log->info("Url to send data: ".$url); my $request_data = { content => $data, headers => { 'Accept' => 'application/json, */*; q=0.1', 'Content-Type' => 'application/json; charset=UTF-8', 'X-API-Key' => $self->{api_key}, }, }; if ( $url->scheme eq 'dryrun' ) { $self->{debug} and print STDERR "Dryrun - not sending data\n"; return { success => 1, url => "$url", status => 200, reason => 'Dryrun requested - echoing post data', content => $request_data->{content}, request_data => $request_data, }; } if ( $self->{debug} ) { print STDERR "DataStore url " . $url . "\n"; } my $response = $self->{ua}->request( 'POST', $url, $request_data ); my ( $status, $reason ); if ($response) { $status = $response->{status}; $reason = $response->{reason}; if ( $status == INTERNAL_EXCEPTION ) { croak "Exception caught sending webapp request: $response->{content}\n"; } if ( $self->{debug} ) { print STDERR "DataStore response content: " . $response->{content}; } } if ( not $response->{success} ) { croak "Failed to post content: $data, Status: " . $response->{status} . " Reason: ". $response->{reason}; } return $response; } 1;