Skip to content

Commit 584addb

Browse files
andxuAndy Xu(devdiv)
and
Andy Xu(devdiv)
authored
Proxy refactor step 2 (#1295)
* 1. rename MavenAuthUtils to MavenAuthManager 2. hide AzureAuthManager from public access(use MavenAuthManager instead) 3. tune the code for determine default subscription Co-authored-by: Andy Xu(devdiv) <andxu@microsoft>
1 parent da9a452 commit 584addb

File tree

7 files changed

+60
-67
lines changed

7 files changed

+60
-67
lines changed

azure-maven-plugin-lib/src/main/java/com/microsoft/azure/maven/AbstractAzureMojo.java

+12-15
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,10 @@
2626
import com.microsoft.azure.maven.telemetry.TelemetryConfiguration;
2727
import com.microsoft.azure.maven.telemetry.TelemetryProxy;
2828
import com.microsoft.azure.maven.utils.CustomTextIoStringListReader;
29-
import com.microsoft.azure.maven.utils.MavenAuthUtils;
29+
import com.microsoft.azure.maven.auth.MavenAuthManager;
3030
import com.microsoft.azure.maven.utils.MavenUtils;
31+
import com.microsoft.azure.maven.utils.ProxyUtils;
3132
import com.microsoft.azure.maven.utils.SystemPropertyUtils;
32-
import com.microsoft.azure.toolkit.lib.common.proxy.ProxyManager;
3333
import com.microsoft.azure.tools.auth.util.AzureEnvironmentUtils;
3434
import com.microsoft.azure.tools.auth.exception.AzureLoginException;
3535
import com.microsoft.azure.tools.auth.model.AzureCredentialWrapper;
@@ -310,7 +310,7 @@ protected String getAuthType() {
310310
return StringUtils.firstNonBlank(auth == null ? null : auth.getType(), authType);
311311
}
312312

313-
protected String selectSubscription(Azure az, Subscription[] subscriptions) throws AzureExecutionException {
313+
protected String selectSubscription(Subscription[] subscriptions) throws AzureExecutionException {
314314
if (subscriptions.length == 0) {
315315
throw new AzureExecutionException("Cannot find any subscriptions in current account.");
316316
}
@@ -319,12 +319,10 @@ protected String selectSubscription(Azure az, Subscription[] subscriptions) thro
319319
TextUtils.blue(SubscriptionOption.getSubscriptionName(subscriptions[0]))));
320320
return subscriptions[0].subscriptionId();
321321
}
322-
final String defaultId = Optional.ofNullable(az.getCurrentSubscription()).map(Subscription::subscriptionId).orElse(null);
323322
final List<SubscriptionOption> wrapSubs = Arrays.stream(subscriptions).map(t -> new SubscriptionOption(t))
324323
.sorted()
325324
.collect(Collectors.toList());
326-
final SubscriptionOption defaultValue = wrapSubs.stream()
327-
.filter(t -> StringUtils.equalsIgnoreCase(t.getSubscriptionId(), defaultId)).findFirst().orElse(null);
325+
final SubscriptionOption defaultValue = wrapSubs.get(0);
328326
final TextIO textIO = TextIoFactory.getTextIO();
329327
final SubscriptionOption subscriptionOptionSelected = new CustomTextIoStringListReader<SubscriptionOption>(() -> textIO.getTextTerminal(), null)
330328
.withCustomPrompt(String.format("Please choose a subscription%s: ",
@@ -342,7 +340,7 @@ protected Azure getOrCreateAzureClient() throws AzureAuthFailureException, Azure
342340
mavenAuthConfiguration.setType(getAuthType());
343341

344342
SystemPropertyUtils.injectCommandLineParameter("auth", mavenAuthConfiguration, MavenAuthConfiguration.class);
345-
azureCredentialWrapper = MavenAuthUtils.login(session, settingsDecrypter, mavenAuthConfiguration);
343+
azureCredentialWrapper = MavenAuthManager.getInstance().login(session, settingsDecrypter, mavenAuthConfiguration);
346344

347345
if (Objects.isNull(azureCredentialWrapper)) {
348346
return null;
@@ -354,11 +352,10 @@ protected Azure getOrCreateAzureClient() throws AzureAuthFailureException, Azure
354352
Log.prompt(String.format(USING_AZURE_ENVIRONMENT, TextUtils.cyan(environmentName)));
355353
}
356354
Log.info(azureCredentialWrapper.getCredentialDescription());
357-
final Azure tempAzure = Azure.configure()
358-
.authenticate(azureCredentialWrapper.getAzureTokenCredentials()).withDefaultSubscription();
359-
final PagedList<Subscription> subscriptions = tempAzure.subscriptions().list();
355+
final PagedList<Subscription> subscriptions = Azure.configure()
356+
.authenticate(azureCredentialWrapper.getAzureTokenCredentials()).subscriptions().list();
360357
subscriptions.loadAll();
361-
final String targetSubscriptionId = getTargetSubscriptionId(tempAzure, subscriptions);
358+
final String targetSubscriptionId = getTargetSubscriptionId(getSubscriptionId(), subscriptions);
362359
checkSubscription(subscriptions, targetSubscriptionId);
363360
azureCredentialWrapper.withDefaultSubscriptionId(targetSubscriptionId);
364361
return AzureClientFactory.getAzureClient(azureCredentialWrapper, getUserAgent());
@@ -445,7 +442,7 @@ public String getAuthMethod() {
445442
public void execute() throws MojoExecutionException {
446443
try {
447444
// init proxy manager
448-
ProxyManager.getInstance().init();
445+
ProxyUtils.initProxy(Optional.ofNullable(this.session).map(s -> s.getRequest()).orElse(null));
449446

450447
// Work around for Application Insights Java SDK:
451448
// Sometimes, NoClassDefFoundError will be thrown even after Maven build is completed successfully.
@@ -619,9 +616,9 @@ protected interface RunnableWithException {
619616
}
620617
//endregion
621618

622-
private String getTargetSubscriptionId(Azure azure2, PagedList<Subscription> subscriptions) throws IOException, AzureExecutionException {
619+
private String getTargetSubscriptionId(String defaultSubscriptionId, PagedList<Subscription> subscriptions) throws IOException, AzureExecutionException {
623620
final List<String> subsIdList = subscriptions.stream().map(Subscription::subscriptionId).collect(Collectors.toList());
624-
String targetSubscriptionId = StringUtils.firstNonBlank(this.subscriptionId, azureCredentialWrapper.getDefaultSubscriptionId());
621+
String targetSubscriptionId = defaultSubscriptionId;
625622

626623
if (StringUtils.isBlank(targetSubscriptionId) && ArrayUtils.isNotEmpty(azureCredentialWrapper.getFilteredSubscriptionIds())) {
627624
final Collection<String> filteredSubscriptions = StringListUtils.intersectIgnoreCase(subsIdList,
@@ -632,7 +629,7 @@ private String getTargetSubscriptionId(Azure azure2, PagedList<Subscription> sub
632629
}
633630

634631
if (StringUtils.isBlank(targetSubscriptionId)) {
635-
return selectSubscription(azure2, subscriptions.toArray(new Subscription[0]));
632+
return selectSubscription(subscriptions.toArray(new Subscription[0]));
636633
}
637634
return targetSubscriptionId;
638635
}

azure-maven-plugin-lib/src/main/java/com/microsoft/azure/maven/utils/MavenAuthUtils.java renamed to azure-maven-plugin-lib/src/main/java/com/microsoft/azure/maven/auth/MavenAuthManager.java

+11-6
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
* license information.
55
*/
66

7-
package com.microsoft.azure.maven.utils;
7+
package com.microsoft.azure.maven.auth;
88

99
import com.microsoft.azure.common.exceptions.AzureExecutionException;
1010
import com.microsoft.azure.maven.exception.MavenDecryptException;
@@ -25,11 +25,17 @@
2525

2626
import static com.microsoft.azure.maven.auth.MavenSettingHelper.buildAuthConfigurationByServerId;
2727

28-
public class MavenAuthUtils {
28+
public class MavenAuthManager extends AzureAuthManager {
2929
private static final String INVALID_AZURE_ENVIRONMENT = "Invalid environment string '%s', please replace it with one of " +
30-
"\"Azure\", \"AzureChina\", \"AzureGermany\", \"AzureUSGovernment\",.";
30+
"\"Azure\", \"AzureChina\", \"AzureGermany\", \"AzureUSGovernment\",.";
3131

32-
public static AzureCredentialWrapper login(MavenSession session, SettingsDecrypter settingsDecrypter, @Nonnull MavenAuthConfiguration auth)
32+
private static MavenAuthManager mavenAuthManager = new MavenAuthManager();
33+
34+
public static MavenAuthManager getInstance() {
35+
return mavenAuthManager;
36+
}
37+
38+
public AzureCredentialWrapper login(MavenSession session, SettingsDecrypter settingsDecrypter, @Nonnull MavenAuthConfiguration auth)
3339
throws AzureExecutionException, MavenDecryptException, InvalidConfigurationException {
3440
final String serverId = auth.getServerId();
3541
final AuthConfiguration authConfiguration;
@@ -41,8 +47,7 @@ public static AzureCredentialWrapper login(MavenSession session, SettingsDecrypt
4147
: "in <auth> configuration.";
4248
throw new AzureExecutionException(String.format("%s %s", ex.getMessage(), messagePostfix));
4349
}
44-
ProxyUtils.configureProxy(session.getRequest());
45-
return AzureAuthManager.getAzureCredentialWrapper(authConfiguration).toBlocking().value();
50+
return super.login(authConfiguration).toBlocking().value();
4651
}
4752

4853
private static AuthConfiguration convertToAuthConfiguration(MavenAuthConfiguration mavenAuthConfiguration)

azure-maven-plugin-lib/src/main/java/com/microsoft/azure/maven/utils/ProxyUtils.java

+3-2
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,11 @@
2020
import java.util.Objects;
2121

2222
public class ProxyUtils {
23-
public static void configureProxy(MavenExecutionRequest request) {
23+
public static void initProxy(MavenExecutionRequest request) {
2424
final ProxyManager proxyManager = ProxyManager.getInstance();
25+
proxyManager.init();
2526
String source = "system";
26-
if (Objects.isNull(proxyManager.getProxy())) {
27+
if (!proxyManager.forceUseSystemProxy() && request != null) {
2728
final List<Proxy> mavenProxies = request.getProxies();
2829
if (CollectionUtils.isNotEmpty(mavenProxies)) {
2930
final Proxy mavenProxy = mavenProxies.stream().filter(

azure-spring-cloud-maven-plugin/src/main/java/com/microsoft/azure/maven/springcloud/AbstractMojoBase.java

+5-4
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@
1717
import com.microsoft.azure.maven.springcloud.config.ConfigurationParser;
1818
import com.microsoft.azure.maven.telemetry.AppInsightHelper;
1919
import com.microsoft.azure.maven.telemetry.MojoStatus;
20-
import com.microsoft.azure.maven.utils.MavenAuthUtils;
21-
import com.microsoft.azure.toolkit.lib.common.proxy.ProxyManager;
20+
import com.microsoft.azure.maven.auth.MavenAuthManager;
21+
import com.microsoft.azure.maven.utils.ProxyUtils;
2222
import com.microsoft.azure.tools.auth.util.AzureEnvironmentUtils;
2323
import com.microsoft.azure.tools.auth.model.AzureCredentialWrapper;
2424
import com.microsoft.azure.tools.exception.InvalidConfigurationException;
@@ -40,6 +40,7 @@
4040
import java.util.HashMap;
4141
import java.util.Map;
4242
import java.util.Objects;
43+
import java.util.Optional;
4344

4445
import static com.microsoft.azure.maven.springcloud.TelemetryConstants.TELEMETRY_KEY_AUTH_METHOD;
4546
import static com.microsoft.azure.maven.springcloud.TelemetryConstants.TELEMETRY_KEY_CPU;
@@ -149,13 +150,13 @@ public void execute() throws MojoFailureException {
149150
protected void initExecution() throws MojoFailureException, MavenDecryptException, AzureExecutionException,
150151
com.microsoft.azure.tools.auth.exception.InvalidConfigurationException {
151152
// init proxy manager
152-
ProxyManager.getInstance().init();
153+
ProxyUtils.initProxy(Optional.ofNullable(this.session).map(s -> s.getRequest()).orElse(null));
153154
// Init telemetries
154155
initTelemetry();
155156
trackMojoExecution(MojoStatus.Start);
156157
final MavenAuthConfiguration mavenAuthConfiguration = auth == null ? new MavenAuthConfiguration() : auth;
157158
mavenAuthConfiguration.setType(getAuthType());
158-
this.azureCredentialWrapper = MavenAuthUtils.login(session, settingsDecrypter, mavenAuthConfiguration);
159+
this.azureCredentialWrapper = MavenAuthManager.getInstance().login(session, settingsDecrypter, mavenAuthConfiguration);
159160
if (Objects.isNull(azureCredentialWrapper)) {
160161
AppInsightHelper.INSTANCE.trackEvent(INIT_FAILURE);
161162
throw new MojoFailureException(AZURE_INIT_FAIL);

azure-toolkit-libs/azure-toolkit-auth-lib/src/main/java/com/microsoft/azure/tools/auth/AzureAuthManager.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
import java.util.Map;
2929

3030
public class AzureAuthManager {
31-
public static Single<AzureCredentialWrapper> getAzureCredentialWrapper(AuthConfiguration configuration) {
31+
protected Single<AzureCredentialWrapper> login(AuthConfiguration configuration) {
3232
AuthConfiguration auth = MoreObjects.firstNonNull(configuration, new AuthConfiguration());
3333
AzureEnvironmentUtils.setupAzureEnvironment(auth.getEnvironment());
3434
ChainedCredentialRetriever chainedCredentialRetriever = new ChainedCredentialRetriever();

azure-toolkit-libs/azure-toolkit-common-lib/src/main/java/com/microsoft/azure/toolkit/lib/common/proxy/ProxyManager.java

+26-37
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
/*
1+
/**
22
* Copyright (c) Microsoft Corporation. All rights reserved.
33
* Licensed under the MIT License. See License.txt in the project root for
44
* license information.
@@ -9,7 +9,6 @@
99
import com.google.common.base.Preconditions;
1010

1111
import org.apache.commons.lang3.StringUtils;
12-
import org.apache.commons.lang3.reflect.FieldUtils;
1312

1413
import javax.annotation.Nonnull;
1514

@@ -29,7 +28,9 @@
2928
public class ProxyManager {
3029
private static final String PROPERTY_USE_SYSTEM_PROXY = "java.net.useSystemProxies";
3130
private static final int MAX_PORT_NUMBER = 65535;
32-
31+
// isSystemProxyUnset shows whether user specify the proxy through -Djava.net.useSystemProxies
32+
// see: https://docs.oracle.com/javase/8/docs/technotes/guides/net/proxies.html
33+
private static final boolean isSystemProxyUnset = StringUtils.isBlank(System.getProperty(PROPERTY_USE_SYSTEM_PROXY));
3334
@Getter
3435
private Proxy proxy;
3536

@@ -43,15 +44,15 @@ public static ProxyManager getInstance() {
4344

4445
public String getHttpProxyHost() {
4546
if (Objects.nonNull(this.proxy) && proxy.address() instanceof InetSocketAddress) {
46-
InetSocketAddress address = (InetSocketAddress) proxy.address();
47+
final InetSocketAddress address = (InetSocketAddress) proxy.address();
4748
return address.getHostString();
4849
}
4950
return null;
5051
}
5152

5253
public int getHttpProxyPort() {
5354
if (Objects.nonNull(this.proxy) && proxy.address() instanceof InetSocketAddress) {
54-
InetSocketAddress address = (InetSocketAddress) proxy.address();
55+
final InetSocketAddress address = (InetSocketAddress) proxy.address();
5556
return address.getPort();
5657
}
5758
return 0;
@@ -64,32 +65,40 @@ public void configure(@Nonnull String httpProxyHost, @Nonnull Integer httpProxyP
6465
throw new IllegalArgumentException(
6566
String.format("Invalid range of httpProxyPort: '%s', it should be a number between %d and %d", httpProxyPort, 1, MAX_PORT_NUMBER));
6667
}
68+
// proxy conflicting
69+
if (forceUseSystemProxy()) {
70+
throw new IllegalArgumentException("Cannot set the proxy second time when user has specified the proxy through " +
71+
"vm arguments: -Djava.net.useSystemProxies=true.");
72+
}
6773
this.proxy = createHttpProxy(httpProxyHost, httpProxyPort);
74+
replaceDefaultProxySelector();
6875
}
6976

7077
public void init() {
71-
// if user wants to use or not use system proxy explicitly
72-
Proxy systemProxy = getSystemProxy();
73-
if (systemProxy != null) {
74-
this.proxy = systemProxy;
78+
// we need to init at the program start before any internet access
79+
if (isSystemProxyUnset) {
80+
// to make ProxySelector return the system proxy, we need to set java.net.useSystemProxies = true
81+
System.setProperty(PROPERTY_USE_SYSTEM_PROXY, "true");
82+
}
83+
this.proxy = getSystemProxyInner();
84+
if (isSystemProxyUnset) {
85+
System.clearProperty(PROPERTY_USE_SYSTEM_PROXY);
7586
}
76-
this.replaceSystemProxySelector();
7787
}
7888

79-
private void replaceSystemProxySelector() {
80-
final ProxySelector ds = ProxySelector.getDefault();
89+
public boolean forceUseSystemProxy() {
90+
return !isSystemProxyUnset && this.proxy != null;
91+
}
92+
93+
private void replaceDefaultProxySelector() {
8194
ProxySelector.setDefault(new ProxySelector() {
8295
@Override
8396
public List<Proxy> select(URI uri) {
84-
if (Objects.nonNull(ProxyManager.this.proxy)) {
85-
return Collections.singletonList(ProxyManager.this.proxy);
86-
}
87-
return ds.select(uri);
97+
return Collections.singletonList(ProxyManager.this.proxy);
8898
}
8999

90100
@Override
91101
public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
92-
ds.connectFailed(uri, sa, ioe);
93102
}
94103
});
95104
}
@@ -99,26 +108,6 @@ private static Proxy createHttpProxy(String httpProxyHost, Integer httpProxyPort
99108
httpProxyPort)) : null;
100109
}
101110

102-
private static Proxy getSystemProxy() {
103-
boolean isSystemProxyUnset = StringUtils.isBlank(System.getProperty(PROPERTY_USE_SYSTEM_PROXY));
104-
try {
105-
if (isSystemProxyUnset) {
106-
System.setProperty(PROPERTY_USE_SYSTEM_PROXY, "true");
107-
}
108-
return getSystemProxyInner();
109-
} finally {
110-
try {
111-
if (isSystemProxyUnset) {
112-
// revert the influence of System.setProperty(PROPERTY_USE_SYSTEM_PROXY, "true")
113-
FieldUtils.writeStaticField(ProxySelector.getDefault().getClass(), "hasSystemProxies", false, true);
114-
System.clearProperty(PROPERTY_USE_SYSTEM_PROXY);
115-
}
116-
} catch (NullPointerException | IllegalAccessException ex) {
117-
// ignore
118-
}
119-
}
120-
}
121-
122111
@SneakyThrows
123112
private static Proxy getSystemProxyInner() {
124113
final URI uri = new URI("https://login.microsoft.com");

azure-webapp-maven-plugin/src/main/java/com/microsoft/azure/maven/webapp/AbstractWebAppMojo.java

+2-2
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,10 @@
1919
import com.microsoft.azure.management.appservice.WebContainer;
2020
import com.microsoft.azure.maven.AbstractAppServiceMojo;
2121
import com.microsoft.azure.maven.auth.AzureAuthFailureException;
22+
import com.microsoft.azure.maven.auth.MavenAuthManager;
2223
import com.microsoft.azure.maven.model.MavenAuthConfiguration;
2324
import com.microsoft.azure.maven.model.SubscriptionOption2;
2425
import com.microsoft.azure.maven.utils.CustomTextIoStringListReader;
25-
import com.microsoft.azure.maven.utils.MavenAuthUtils;
2626
import com.microsoft.azure.maven.utils.SystemPropertyUtils;
2727
import com.microsoft.azure.maven.webapp.configuration.ContainerSetting;
2828
import com.microsoft.azure.maven.webapp.configuration.Deployment;
@@ -424,7 +424,7 @@ protected AzureAppService getOrCreateAzureAppServiceClient() throws AzureExecuti
424424
try {
425425
final MavenAuthConfiguration mavenAuthConfiguration = auth == null ? new MavenAuthConfiguration() : auth;
426426
mavenAuthConfiguration.setType(getAuthType());
427-
final AzureCredentialWrapper azureCredentialWrapper = MavenAuthUtils.login(session, settingsDecrypter, mavenAuthConfiguration);
427+
final AzureCredentialWrapper azureCredentialWrapper = MavenAuthManager.getInstance().login(session, settingsDecrypter, mavenAuthConfiguration);
428428
if (Objects.isNull(azureCredentialWrapper)) {
429429
return null;
430430
}

0 commit comments

Comments
 (0)