Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug 1774224: User should be prompt with the right message when tokens in azure cli expires. #4707

Merged
merged 4 commits into from
Nov 4, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -764,6 +764,16 @@ public void showInfoNotification(String title, String message) {
PluginUtil.showInfoNotification(title, message);
}

@Override
public void showWarningNotification(String title, String message) {
PluginUtil.showWarnNotification(title, message);
}

@Override
public void showErrorNotification(String title, String message) {
PluginUtil.showErrorNotification(title, message);
}

private static <T> T runFromDispatchThread(Supplier<T> supplier) {
if (ApplicationManager.getApplication().isDispatchThread()) {
return supplier.get();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,4 +158,12 @@ default String showInputDialog(Component component, String message, String title
default void showInfoNotification(String title, String message) {

}

default void showErrorNotification(String title, String message) {

}

default void showWarningNotification(String title, String message) {

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ protected synchronized void refreshItems(SettableFuture<List<Node>> future, bool
refreshItems();
future.set(getChildNodes());
} catch (AzureRuntimeException e) {
DefaultLoader.getUIHelper().showInfoNotification("MS Services - Error Refreshing Nodes", ErrorEnum.getDisplayMessageByCode(e.getCode()));
DefaultLoader.getUIHelper().showErrorNotification("Error occurred while refreshing node", ErrorEnum.getDisplayMessageByCode(e.getCode()));
} catch (Exception e) {
future.setException(e);
} finally {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,34 +23,29 @@
package com.microsoft.tooling.msservices.serviceexplorer.azure.arm;

import com.microsoft.azure.management.resources.ResourceGroup;
import com.microsoft.azure.management.resources.fluentcore.arm.ResourceId;
import com.microsoft.azuretools.azurecommons.helpers.AzureCmdException;
import com.microsoft.azuretools.core.mvp.model.ResourceEx;
import com.microsoft.azuretools.telemetry.TelemetryConstants;
import com.microsoft.azuretools.telemetrywrapper.EventUtil;
import com.microsoft.azuretools.utils.*;
import com.microsoft.tooling.msservices.components.DefaultLoader;
import com.microsoft.tooling.msservices.helpers.collections.ObservableList;
import com.microsoft.tooling.msservices.serviceexplorer.AzureRefreshableNode;
import com.microsoft.tooling.msservices.serviceexplorer.Node;
import com.microsoft.tooling.msservices.serviceexplorer.azure.arm.deployments.DeploymentNode;
import com.microsoft.tooling.msservices.serviceexplorer.azure.webapp.WebAppModule;
import com.microsoft.tooling.msservices.serviceexplorer.azure.webapp.WebAppNode;

import javax.swing.tree.TreePath;
import java.io.IOException;
import java.util.List;

public class ResourceManagementModule extends AzureRefreshableNode implements ResourceManagementModuleView {

private static final String RESOURCE_MANAGEMENT_MODULE_ID = ResourceManagementModule.class.getName();
private static final String ICON_PATH = "arm_resourcegroup.png";
private static final String BASE_MODULE_NAME = "Resource Management";
private final ResourceManagementModulePresenter rmModulePresenter;
private final ResourceManagementModulePresenter<ResourceManagementModule> rmModulePresenter;
public static final Object listenerObj = new Object();

public ResourceManagementModule(Node parent) {
super(RESOURCE_MANAGEMENT_MODULE_ID, BASE_MODULE_NAME, parent, ICON_PATH);
rmModulePresenter = new ResourceManagementModulePresenter();
rmModulePresenter = new ResourceManagementModulePresenter<>();
rmModulePresenter.onAttachView(ResourceManagementModule.this);
createListener();
}
Expand All @@ -59,12 +54,11 @@ public ResourceManagementModule(Node parent) {
protected void refreshItems() throws AzureCmdException {
try {
rmModulePresenter.onModuleRefresh();
} catch (Exception e) {
DefaultLoader.getUIHelper()
.showException("An error occurred while attempting to refresh the resource manage module ",
e, "Azure Services Explorer - Error Refresh resource manage module", false, true);
} catch (final IOException e) {
throw new RuntimeException(e);
} catch (final CanceledByUserException e) {
DefaultLoader.getUIHelper().showWarningNotification("Refreshing cancelled", "You canceled refreshing resource groups.");
}

}

@Override
Expand All @@ -74,8 +68,8 @@ public void removeNode(String sid, String id, Node node) {
removeDirectChildNode(node);
}), (e) -> {
DefaultLoader.getUIHelper()
.showException("An error occurred while attempting to delete the resource group ",
e, "Azure Services Explorer - Error Deleting Resource Group", false, true);
.showException("An error occurred while attempting to delete the resource group",
e, "Azure Explorer - Error Deleting Resource Group", false, true);
});
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/*
* Copyright (c) Microsoft Corporation
*
* All rights reserved.
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
* to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of
* the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
* THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

package com.microsoft.azure.toolkit.lib.common.rest;

import com.google.common.base.Throwables;
import com.microsoft.aad.adal4j.AuthenticationException;
import com.microsoft.azuretools.enums.ErrorEnum;
import com.microsoft.azuretools.exception.AzureRuntimeException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.List;

/**
* Interceptor to handle REST API related exceptions
*/
public class RestExceptionHandlerInterceptor implements Interceptor {
@Override
public Response intercept(final Chain chain) throws IOException {
try {
final Request request = chain.request();
return chain.proceed(request);
} catch (final Exception ex) {
final List<Throwable> exceptions = Throwables.getCausalChain(ex);
if (exceptions.stream().anyMatch(e -> e instanceof UnknownHostException)) {
throw new AzureRuntimeException(ErrorEnum.UNKNOWN_HOST_EXCEPTION);
} else if (exceptions.stream().anyMatch(e -> e instanceof AuthenticationException)) {
throw new AzureRuntimeException(ErrorEnum.INVALID_AUTHENTICATION);
}
throw ex;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,14 @@
public enum ErrorEnum {
UNKNOWN_HOST_EXCEPTION(100000, "Encountered an unknown host exception.",
"It seems you have an unstable network at the moment, please try again when network is available."),
INVALID_AUTHENTICATION(100401, "Invalid authentication",
"Authentication token invalid, sign in again or run \"az login\" if using Azure CLI credential"),
SOCKET_TIMEOUT_EXCEPTION(100002, "Encountered a socket timeout exception.",
"Timeout when accessing azure, please try your operation again."),
FAILED_TO_GET_ACCESS_TOKEN_BY_CLI(100003, "Failed to get access token by Azure CLI command.",
"Failed to get access token, please try to login Azure CLI using 'az login' and try again."),
INVALID_SUBSCRIPTION_CACHE(100004, "Invalid subscription",
"It seems local cache of subscription is expired, please try re-login"),
;

private int errorCode;
Expand Down Expand Up @@ -64,5 +68,4 @@ public static String getDisplayMessageByCode(int code) {
}
throw new IllegalArgumentException(String.format("Not found enum for code: %s", code));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@

package com.microsoft.azuretools.sdkmanage;

import com.google.common.base.Throwables;
import com.microsoft.azure.AzureEnvironment;
import com.microsoft.azure.arm.resources.AzureConfigurable;
import com.microsoft.azure.credentials.AzureTokenCredentials;
Expand All @@ -31,17 +30,16 @@
import com.microsoft.azure.management.appplatform.v2019_05_01_preview.implementation.AppPlatformManager;
import com.microsoft.azure.management.resources.Subscription;
import com.microsoft.azure.management.resources.Tenant;
import com.microsoft.azure.toolkit.lib.common.rest.RestExceptionHandlerInterceptor;
import com.microsoft.azuretools.authmanage.*;
import com.microsoft.azuretools.exception.AzureRuntimeException;
import com.microsoft.azuretools.enums.ErrorEnum;
import com.microsoft.azuretools.exception.AzureRuntimeException;
import com.microsoft.azuretools.telemetry.TelemetryInterceptor;
import com.microsoft.azuretools.utils.AzureRegisterProviderNamespaces;
import com.microsoft.azuretools.utils.Pair;
import org.apache.commons.lang3.StringUtils;
import rx.Observable;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
Expand Down Expand Up @@ -109,7 +107,7 @@ public String getTenantIdBySubscription(String subscriptionId) throws IOExceptio
final Pair<Subscription, Tenant> subscriptionTenantPair = getSubscriptionsWithTenant().stream()
.filter(pair -> pair != null && pair.first() != null && pair.second() != null)
.filter(pair -> StringUtils.equals(pair.first().subscriptionId(), subscriptionId))
.findFirst().orElseThrow(() -> new IOException("Failed to find storage subscription id"));
.findFirst().orElseThrow(() -> new AzureRuntimeException(ErrorEnum.INVALID_SUBSCRIPTION_CACHE));
return subscriptionTenantPair.second().tenantId();
}

Expand All @@ -129,10 +127,10 @@ public List<Pair<Subscription, Tenant>> getSubscriptionsWithTenant() throws IOEx
final Azure.Authenticated authentication = authTenant(getCurrentTenantId());
// could be multi tenant - return all subscriptions for the current account
final List<Tenant> tenants = getTenants(authentication);
for (Tenant tenant : tenants) {
for (final Tenant tenant : tenants) {
final Azure.Authenticated tenantAuthentication = authTenant(tenant.tenantId());
final List<Subscription> tenantSubscriptions = getSubscriptions(tenantAuthentication);
for (Subscription subscription : tenantSubscriptions) {
for (final Subscription subscription : tenantSubscriptions) {
subscriptions.add(new Pair<>(subscription, tenant));
}
}
Expand Down Expand Up @@ -242,51 +240,42 @@ public List<Subscription> getSubscriptions(String tenantId) {
return getSubscriptions(authTenant(tenantId));
}

private List<Subscription> getSubscriptions(Azure.Authenticated tenantAuthentication) {
return tenantAuthentication.subscriptions().listAsync()
.onErrorResumeNext(err -> {
LOGGER.warning(err.getMessage());
return Observable.empty();
})
private List<Subscription> getSubscriptions(Azure.Authenticated authentication) {
return authentication.subscriptions().listAsync()
.toList()
.toBlocking()
.singleOrDefault(Collections.emptyList());
}

private List<Tenant> getTenants(Azure.Authenticated authentication) {
try {
return authentication.tenants().listAsync()
.toList()
.toBlocking()
.singleOrDefault(Collections.emptyList());
} catch (Exception err) {
LOGGER.warning(Throwables.getStackTraceAsString(err));
if (Throwables.getCausalChain(err).stream().filter(e -> e instanceof UnknownHostException).count() > 0) {
throw new AzureRuntimeException(ErrorEnum.UNKNOWN_HOST_EXCEPTION);
} else if (err instanceof AzureRuntimeException) {
throw err;
}
return Collections.emptyList();
}
return authentication.tenants().listAsync()
.toList()
.toBlocking()
.singleOrDefault(Collections.emptyList());
}

protected Azure.Authenticated authTenant(String tenantId) {
final AzureTokenCredentials credentials = getCredentials(tenantId);
return Azure.configure()
.withInterceptor(new TelemetryInterceptor())
.withInterceptor(new RestExceptionHandlerInterceptor())
.withUserAgent(CommonSettings.USER_AGENT)
.authenticate(credentials);
}

protected AppPlatformManager authSpringCloud(String subscriptionId, String tenantId) {
final AzureTokenCredentials credentials = getCredentials(tenantId);
return buildAzureManager(AppPlatformManager.configure())
.withInterceptor(new TelemetryInterceptor())
.withInterceptor(new RestExceptionHandlerInterceptor())
.authenticate(credentials, subscriptionId);
}

protected InsightsManager authApplicationInsights(String subscriptionId, String tenantId) {
final AzureTokenCredentials credentials = getCredentials(tenantId);
return buildAzureManager(InsightsManager.configure())
.withInterceptor(new TelemetryInterceptor())
.withInterceptor(new RestExceptionHandlerInterceptor())
.authenticate(credentials, subscriptionId);
}
}