Browseable/Store/Patroni.pm untested

filter: Statementstmt 0.0% 0 / 134 Branchbran 0.0% 0 / 42 Conditioncond 0.0% 0 / 67 MC/DCmcdc 0.0% 0 / 37 Subroutinesub 0.0% 0 / 15 Podpod 0.0% 0 / 9 totaltotal 0.0% 0 / 304 CC 22 SCAR 41.8
CC
22
Cov
0%
checkMaster
156.0
connection
56.0
_try
12.0
CRAP 65.1
1 package Apache::Session::Browseable::Store::Patroni;
2  
3 use strict;
4  
5 use DBI;
6 use Apache::Session::Store::Postgres;
7  
8 our @ISA = qw(Apache::Session::Store::Postgres);
9 our $VERSION = '1.3.19';
10  
11 # Cache structure per DataSource:
12 # {
13 # leader => { host => '...', port => '...', time => ... },
14 # lastFailure => timestamp,
15 # }
16 our %patroniCache;
17  
18 sub connection {
19 my $self = shift;
20 my $session = shift;
21  
22 return if ( defined $self->{dbh} );
23  
24 $self->{'table_name'} =
25 $session->{args}->{TableName} || $Apache::Session::Store::DBI::TableName;
26  
27 if ( exists $session->{args}->{Handle} ) {
28 $self->{dbh} = $session->{args}->{Handle};
29 $self->{commit} = $session->{args}->{Commit};
30 return;
31 }
32  
33 # Store original DataSource as cache key
34 my $originalDataSource = $session->{args}->{DataSource};
35 $self->{_originalDataSource} = $originalDataSource;
36  
37 # Use cached leader if available and not expired
38 my $cache = $patroniCache{$originalDataSource} || {};
39 my $cacheTTL = $session->{args}->{PatroniCacheTTL} || 60;
40  
41 if ( $cache->{leader}
42 and $cache->{leader}->{time}
43 and ( time() - $cache->{leader}->{time} ) < $cacheTTL )
44 {
45 $session->{args}->{DataSource} =
46 _buildDataSource( $originalDataSource, $cache->{leader} );
47 }
48  
49 foreach ( 0 .. 1 ) {
50 (
51 $self->checkMaster( $session->{args} )
52 or warn "Patroni check failed"
53 ) if $self->{failure};
54 eval {
55 $self->{dbh} = DBI->connect(
56 $session->{args}->{DataSource},
57 $session->{args}->{UserName},
58 $session->{args}->{Password},
59 { RaiseError => 1, AutoCommit => 0 }
60 ) || die $DBI::errstr;
61 };
62 if ( $@ and !$_ ) {
63 $self->{failure} = 1;
64 }
65 else {
66 last;
67 }
68 }
69 die $@ if $@;
70  
71 #If we open the connection, we close the connection
72 $self->{disconnect} = 1;
73  
74 #the programmer has to tell us what commit policy to use
75 $self->{commit} = $session->{args}->{Commit} // 1;
76 }
77  
78 sub _try {
79 my $self = shift;
80 my $sub = shift;
81 my $res;
82  
83 foreach ( 0 .. 1 ) {
84 $res =
85 eval { Apache::Session::Store::Postgres->can($sub)->( $self, @_ ) };
86 if ( $@ and $@ !~ /Object does not exist/ and !$_ ) {
87 $self->{failure} = 1;
88 $self->DESTROY;
89 delete $self->{"${sub}_sth"};
90 delete $self->{dbh};
91 }
92 else {
93 last;
94 }
95 }
96 die $@ if $@;
97 return $res;
98 }
99  
100 sub insert {
101 my $self = shift;
102 return $self->_try( 'insert', @_ );
103 }
104  
105 sub update {
106 my $self = shift;
107 return $self->_try( 'update', @_ );
108 }
109  
110 sub materialize {
111 my $self = shift;
112 return $self->_try( 'materialize', @_ );
113 }
114  
115 sub remove {
116 my $self = shift;
117 return $self->_try( 'remove', @_ );
118 }
119  
120 sub checkMaster {
121 my ( $self, $args ) = @_;
122 delete $self->{failure};
123  
124 my $originalDataSource =
125 $self->{_originalDataSource} || $args->{DataSource};
126 my $cache = $patroniCache{$originalDataSource} ||= {};
127  
128 # Circuit breaker: avoid hammering Patroni API if it's failing
129 my $circuitBreakerDelay = $args->{PatroniCircuitBreakerDelay} || 30;
130 if ( $cache->{lastFailure}
131 and ( time() - $cache->{lastFailure} ) < $circuitBreakerDelay )
132 {
133 # Circuit breaker active, try cached leader as fallback
134 return $self->_useCachedLeader( $args, $originalDataSource,
135 "Circuit breaker active" );
136 }
137  
138 require JSON;
139 require LWP::UserAgent;
140 require IO::Socket::SSL;
141  
142 # SSL verification: secure by default, can be disabled with PatroniVerifySSL => 0
143 my $verify_ssl = $args->{PatroniVerifySSL} // 1;
144 my %ssl_opts;
145 if ($verify_ssl) {
146 %ssl_opts = (
147 verify_hostname => 1,
148 SSL_verify_mode => &IO::Socket::SSL::SSL_VERIFY_PEER,
149 ( $args->{PatroniSSLCAFile} ? ( SSL_ca_file => $args->{PatroniSSLCAFile} ) : () ),
150 ( $args->{PatroniSSLCAPath} ? ( SSL_ca_path => $args->{PatroniSSLCAPath} ) : () ),
151 );
152 }
153 else {
154 %ssl_opts = (
155 verify_hostname => 0,
156 SSL_verify_mode => &IO::Socket::SSL::SSL_VERIFY_NONE,
157 );
158 }
159  
160 my $ua = LWP::UserAgent->new(
161 env_proxy => 1,
162 ssl_opts => \%ssl_opts,
163 timeout => $args->{PatroniTimeout} || 3,
164 );
165 my $res;
166  
167 foreach my $patroniUrl ( split /[,\s]\s*/,
168 ( $args->{PatroniUrl} || $args->{patroniUrl} ) )
169 {
170 my $resp = $ua->get($patroniUrl);
171 if ( $resp->is_success ) {
172 my $c = eval { JSON::from_json( $resp->decoded_content ) };
173 if ( $@ or !$c->{members} or ref( $c->{members} ) ne 'ARRAY' ) {
174 print STDERR "Bad response from $patroniUrl: "
175 . $resp->decoded_content . "\n";
176 next;
177 }
178  
179 my @leaders = grep { $_->{role} eq 'leader' } @{ $c->{members} };
180  
181 # Check for split-brain scenario
182 if ( @leaders > 1 ) {
183 my $leadersList =
184 join( ', ', map { "$_->{host}:$_->{port}" } @leaders );
185 print STDERR
186 "Multiple leaders detected (split-brain) from $patroniUrl"
187 . " - Leaders: $leadersList\n";
188 next;
189 }
190  
191 my ($leader) = @leaders;
192 unless ($leader) {
193 print STDERR "No leader found from $patroniUrl: "
194 . $resp->decoded_content . "\n";
195 next;
196 }
197  
198 # Validate leader has required fields
199 unless ( defined $leader->{host} && defined $leader->{port} ) {
200 print STDERR "Leader missing host or port from $patroniUrl: "
201 . $resp->decoded_content . "\n";
202 next;
203 }
204  
205 # Check leader health state
206 if ( $leader->{state} && $leader->{state} ne 'running' ) {
207 print STDERR
208 "Leader not in running state (state=$leader->{state})"
209 . " from $patroniUrl\n";
210 next;
211 }
212  
213 # Cache the leader info
214 $cache->{leader} = {
215 host => $leader->{host},
216 port => $leader->{port},
217 time => time()
218 };
219  
220 # Reset circuit breaker on success
221 delete $cache->{lastFailure};
222  
223 $args->{DataSource} =
224 _buildDataSource( $originalDataSource, $leader );
225 $res = 1;
226 last;
227 }
228 }
229  
230 # If API failed, record for circuit breaker and try cached leader
231 unless ($res) {
232 $cache->{lastFailure} = time();
233 $res = $self->_useCachedLeader( $args, $originalDataSource,
234 "Patroni API unavailable" );
235 }
236  
237 return $res;
238 }
239  
240 # Use cached leader as fallback
241 sub _useCachedLeader {
242 my ( $self, $args, $originalDataSource, $reason ) = @_;
243  
244 my $cache = $patroniCache{$originalDataSource} || {};
245 my $cacheTTL = $args->{PatroniCacheTTL} || 60;
246  
247 if ( $cache->{leader}
248 and $cache->{leader}->{time}
249 and ( time() - $cache->{leader}->{time} ) < $cacheTTL )
250 {
251 my $age = time() - $cache->{leader}->{time};
252 print STDERR "$reason, using cached leader (${age}s old)\n";
253 $args->{DataSource} =
254 _buildDataSource( $originalDataSource, $cache->{leader} );
255 return 1;
256 }
257 return 0;
258 }
259  
260 # Build DataSource string with new host/port
261 sub _buildDataSource {
262 my ( $originalDataSource, $leader ) = @_;
263  
264 my $chain = $originalDataSource;
265  
266 # Remove existing host/port parameters
267 $chain =~ s/;\s*host=[^;]+//gi;
268 $chain =~ s/;\s*port=[^;]+//gi;
269 $chain =~ s/\s+host=[^\s;]+//gi;
270 $chain =~ s/\s+port=[^\s;]+//gi;
271  
272 # Clean up trailing semicolons
273 $chain =~ s/;+$//;
274  
275 # Add new host and port
276 my $separator = ( $chain =~ /:$/ ) ? '' : ';';
277 return "${chain}${separator}host=$leader->{host};port=$leader->{port}";
278 }
279  
280 1;