Created
April 9, 2024 12:33
-
-
Save frobware/72c30ee8bfdfbc0e347d3bab27998b96 to your computer and use it in GitHub Desktop.
Replace 'weight 256' with 'weight 1' for backends with a single server entry
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use strict; | |
use warnings; | |
use Getopt::Long; | |
use Digest::MD5 qw(md5_hex); | |
my $obfuscate = 0; # No obfuscation by default. | |
my $fix_singular_weight256 = 0; # Conditionally rewrite 'weight 256' | |
GetOptions( | |
'o' => \$obfuscate, | |
'f' => \$fix_singular_weight256 | |
) or die "Error in command line arguments\n"; | |
# Flag to indicate whether the marker has been encountered. | |
my $found_marker = 0; | |
# Accumulate backend block lines here. | |
my @backend_lines = (); | |
while (my $line = <>) { | |
if ($line =~ /^##-------------- app level backends ----------------$/) { | |
# Print accumulated lines for the last backend block before | |
# the marker. | |
if (@backend_lines) { | |
print process_backend_block(@backend_lines); | |
@backend_lines = (); | |
} | |
print $line; | |
$found_marker = 1; | |
next; | |
} | |
if ($found_marker) { | |
if ($line =~ /^backend /) { | |
# Process and print the previous backend block if we're | |
# starting a new one. | |
if (@backend_lines) { | |
print process_backend_block(@backend_lines); | |
@backend_lines = (); | |
} | |
} | |
push @backend_lines, $line; | |
} else { | |
# Print lines directly before the marker is found. | |
print $line; | |
} | |
} | |
# Process any remaining backend block after the loop terminates. | |
if (@backend_lines) { | |
print process_backend_block(@backend_lines); | |
} | |
sub process_backend_block { | |
my @lines = @_; | |
my $block = join('', @lines); | |
# Count server entries and check for the specific weight | |
# condition. | |
my $server_count = grep { /^\s*server\s+/ } @lines; | |
my $has_weight_256 = grep { /weight\s+256/ } @lines; | |
if ($fix_singular_weight256 && $server_count == 1 && $has_weight_256) { | |
# Only apply the weight change if there's exactly one server | |
# with weight 256. | |
$block =~ s/(weight\s+)256/${1}1 #FIXED/; | |
} | |
if ($obfuscate) { | |
# Apply obfuscation to the backend name. | |
$block =~ s/^backend\s+(\S+)/"backend " . md5_hex($1)/em; | |
} | |
return $block; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment