[pmg-devel] [PATCH pmg-api 1/2] add lwp_user_agent to PMG::Utils

Stoiko Ivanov s.ivanov at proxmox.com
Tue Nov 17 09:54:00 CET 2020


The sub returns a LWP::UserAgent instance with properly configured
http-proxy settings (and a custom UserAgent identifier).

refactored from API2::APT, since we need it for updating KAM.cf.

Signed-off-by: Stoiko Ivanov <s.ivanov at proxmox.com>
---
 src/PMG/API2/APT.pm | 14 ++------------
 src/PMG/Utils.pm    | 18 ++++++++++++++++++
 2 files changed, 20 insertions(+), 12 deletions(-)

diff --git a/src/PMG/API2/APT.pm b/src/PMG/API2/APT.pm
index 51b998f..09b11e5 100644
--- a/src/PMG/API2/APT.pm
+++ b/src/PMG/API2/APT.pm
@@ -8,7 +8,6 @@ use File::stat ();
 use IO::File;
 use File::Basename;
 use JSON;
-use LWP::UserAgent;
 
 use PVE::Tools qw(extract_param);
 use PVE::SafeSyslog;
@@ -20,6 +19,7 @@ use PVE::JSONSchema qw(get_standard_option);
 use PMG::RESTEnvironment;
 use PMG::pmgcfg;
 use PMG::Config;
+use PMG::Utils;
 
 use AptPkg::Cache;
 use AptPkg::Version;
@@ -429,21 +429,11 @@ __PACKAGE__->register_method({
 
 	my $data = "";
 
-	my $pmg_cfg = PMG::Config->new();
-	my $proxy = $pmg_cfg->get('admin', 'http_proxy');
-
-	my $ua = LWP::UserAgent->new;
-	$ua->agent("PMG/1.0");
+	my $ua = PMG::Utils::lwp_user_agent();
 	$ua->timeout(10);
 	$ua->max_size(1024*1024);
 	$ua->ssl_opts(verify_hostname => 0); # don't care for changelogs
 
-	if ($proxy) {
-	    $ua->proxy(['http', 'https'], $proxy);
-	} else {
-	    $ua->env_proxy;
-	}
-
 	my $username;
 	my $pw;
 
diff --git a/src/PMG/Utils.pm b/src/PMG/Utils.pm
index d0654e1..844cb96 100644
--- a/src/PMG/Utils.pm
+++ b/src/PMG/Utils.pm
@@ -10,6 +10,7 @@ use File::stat;
 use POSIX qw(strftime);
 use File::stat;
 use File::Basename;
+use LWP::UserAgent;
 use MIME::Entity;
 use MIME::Words;
 use MIME::Parser;
@@ -1417,4 +1418,21 @@ sub reload_smtp_filter {
     return kill (10, $pid); # send SIGUSR1
 }
 
+# returns a LWP::UserAgent instance with option proxy from the config
+sub lwp_user_agent {
+    my $pmg_cfg = PMG::Config->new();
+    my $proxy = $pmg_cfg->get('admin', 'http_proxy');
+
+    my $ua = LWP::UserAgent->new;
+    $ua->agent("PMG/1.0");
+
+    if ($proxy) {
+	$ua->proxy(['http', 'https'], $proxy);
+    } else {
+	$ua->env_proxy;
+    }
+
+    return $ua;
+}
+
 1;
-- 
2.20.1





More information about the pmg-devel mailing list