Hi, to everyone. I'm trying to implement a handler in order to use it in my system.
What for:
There are some scripts that using my server as a balancer in order to split a traffic between multiple external proxy servers. External servers are rented and traffic allowed to go through them is limited, so sometimes we are running out of traffic, but scripts just need to keep going, so traffic must to bypass these proxies somehow.Idea:
I want to implement LWP based user agent that will be able to dynamically construct requests. I think this shouldallow to:
- split traffic between external parent proxies, randomly
- rewrite UserAgent string dynamically,
- mark proxies that receiving a special message that indicates about running out of traffic, as DISABLED allowing system to stop using them for some period of time.
Implementation:
UserAgent strings and proxy-list will be loaded from files into "@agents" and "@routes" arrays accordingly, then array elements that are not containing "DISABLED" substring will be copied to "@usable" array.Before each request got from a client will be retrieved with LWPUserAgent:
All elements except elements containg "DISABLED" substring, must be copied from "@routes" array to "@usable" array.
A handler must be called and this handler must to choose a random external proxy from the array ("@usable"), add authorization header, insert random UserAgent string (from the @agents array) and execute this request. If request fails due to a traffic limit, (this event can be detected by a "Sorry" substring and "302 redirect" in it) this parent proxy will be marked as "DISABLED" in "@routes" array, and excluded from using, but this will be done somewhere beyond this handler
Script
use LWP::UserAgent; my (@agents,@routes,@usable); open( AGENTS, "<", "/etc/handler/ua.cfg" ); while( <AGENTS> ) { s/#.*//; next if /^(\s)*$/; chomp; push @agents, $_; } close(AGENTS); open( ROUTES, "<", "/etc/handler/routes.cfg" ); while( <ROUTES> ) { chomp; s/#.*//; next if /^(\s)*$/; my ( $ip, $port, $login, $password) = split / /, $_ push @routes, "http://$_:$port/,ENABLED"; } close(ROUTES); $ua = LWP::UserAgent->new(); sub makerequest { my($request, $ua, $h) = @_; $request = my while (@routes) { next if m/DISABLED/; push @usable, $_; } my $i = $#agents + 1; $i = rand($i); $i = int $i; my $j = $#usable + 1; $j = rand($j); $j = int $j; $routes[$j] =~ s/\,ENABLED//; $ua->proxy(['http'],$usable[$j]); $h = $ua->proxy_authorization_basic("proxy_user", "proxy_password"); $ua->agent($agents[$i]); $ua->timeout(10); ....................... } $ua->add_handler( prepare_request => \&makerequest) ............
I'm still new to perl and my question may to seem dumb for someone, but my question is, what I need to do next in order to implement things mentioned above? Thanks, in advance.
In reply to LWP request construction. by kazak
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |