Search in sources :

Example 1 with Operation

use of com.microsoft.azuretools.telemetrywrapper.Operation in project azure-tools-for-java by Microsoft.

the class CreateRedisCacheForm method okPressed.

@Override
protected void okPressed() {
    try {
        RedisCacheUtil.doValidate(currentSub, dnsNameValue, selectedLocationValue, selectedResGrpValue, selectedPriceTierValue);
        if (newResGrp) {
            for (String resGrp : sortedGroups) {
                if (selectedResGrpValue.equals(resGrp)) {
                    throw new InvalidFormDataException("The resource group " + selectedResGrpValue + " is not available");
                }
            }
        }
    } catch (InvalidFormDataException e) {
        MessageDialog.openError(getShell(), "Form Validation Error", e.getMessage());
        return;
    }
    RedisConfig config = getData();
    final Runnable runnable = () -> {
        final Operation operation = TelemetryManager.createOperation(REDIS, CREATE_REDIS);
        try {
            operation.start();
            new CreateRedisTask(config).execute();
            if (onCreate != null) {
                onCreate.run();
            }
        } catch (Exception ex) {
            EventUtil.logError(operation, ErrorType.userError, ex, null, null);
            operation.complete();
            MessageDialog.openError(getShell(), String.format(MessageHandler.getResourceString(resourceBundle, CREATING_ERROR_INDICATOR_FORMAT), dnsNameValue), ex.getMessage());
            LOG.log(String.format(MessageHandler.getResourceString(resourceBundle, CREATING_ERROR_INDICATOR_FORMAT), dnsNameValue), ex);
        }
    };
    String progressMessage = Node.getProgressMessage(AzureActionEnum.CREATE.getDoingName(), RedisCacheModule.MODULE_NAME, config.getName());
    AzureTaskManager.getInstance().runInBackground(new AzureTask<>(null, progressMessage, false, runnable));
    super.okPressed();
}
Also used : InvalidFormDataException(com.microsoft.azuretools.azurecommons.exceptions.InvalidFormDataException) Operation(com.microsoft.azuretools.telemetrywrapper.Operation) InvalidFormDataException(com.microsoft.azuretools.azurecommons.exceptions.InvalidFormDataException) IOException(java.io.IOException) RedisConfig(com.microsoft.azure.toolkit.redis.RedisConfig)

Example 2 with Operation

use of com.microsoft.azuretools.telemetrywrapper.Operation in project azure-tools-for-java by Microsoft.

the class DockerRunDialog method execute.

private void execute() {
    Operation operation = TelemetryManager.createOperation(WEBAPP, DEPLOY_WEBAPP_DOCKERLOCAL);
    Observable.fromCallable(() -> {
        operation.start();
        ConsoleLogger.info("Starting job ...  ");
        if (basePath == null) {
            ConsoleLogger.error("Project base path is null.");
            throw new FileNotFoundException("Project base path is null.");
        }
        // locate artifact to specified location
        String targetFilePath = dataModel.getTargetPath();
        ConsoleLogger.info(String.format("Locating artifact ... [%s]", targetFilePath));
        // validate dockerfile
        Path targetDockerfile = Paths.get(dataModel.getDockerFilePath());
        ConsoleLogger.info(String.format("Validating dockerfile ... [%s]", targetDockerfile));
        if (!targetDockerfile.toFile().exists()) {
            throw new FileNotFoundException("Dockerfile not found.");
        }
        // replace placeholder if exists
        String content = new String(Files.readAllBytes(targetDockerfile));
        content = content.replaceAll(Constant.DOCKERFILE_ARTIFACT_PLACEHOLDER, Paths.get(basePath).toUri().relativize(Paths.get(targetFilePath).toUri()).getPath());
        Files.write(targetDockerfile, content.getBytes());
        // build image
        String imageNameWithTag = String.format("%s:%s", dataModel.getImageName(), dataModel.getTagName());
        ConsoleLogger.info(String.format("Building image ...  [%s]", imageNameWithTag));
        DockerClient docker = DockerUtil.getDockerClient(dataModel.getDockerHost(), dataModel.isTlsEnabled(), dataModel.getDockerCertPath());
        DockerUtil.ping(docker);
        DockerUtil.buildImage(docker, imageNameWithTag, targetDockerfile.getParent(), targetDockerfile.getFileName().toString(), new DockerProgressHandler());
        // create a container
        final String containerServerPort = StringUtils.firstNonEmpty(getPortFromDockerfile(content), getPortByArtifact(targetFilePath));
        ConsoleLogger.info(Constant.MESSAGE_CREATING_CONTAINER);
        String containerId = DockerUtil.createContainer(docker, String.format("%s:%s", dataModel.getImageName(), dataModel.getTagName()), containerServerPort);
        ConsoleLogger.info(String.format(Constant.MESSAGE_CONTAINER_INFO, containerId));
        // start container
        ConsoleLogger.info(Constant.MESSAGE_STARTING_CONTAINER);
        Container container = DockerUtil.runContainer(docker, containerId);
        DockerRuntime.getInstance().setRunningContainerId(basePath, container.id(), dataModel);
        // props
        String hostname = new URI(dataModel.getDockerHost()).getHost();
        ImmutableList<PortMapping> ports = container.ports();
        String publicPort = null;
        if (ports != null) {
            for (Container.PortMapping portMapping : ports) {
                if (StringUtils.equalsIgnoreCase(containerServerPort, String.valueOf(portMapping.privatePort()))) {
                    publicPort = String.valueOf(portMapping.publicPort());
                }
            }
        }
        ConsoleLogger.info(String.format(Constant.MESSAGE_CONTAINER_STARTED, (hostname != null ? hostname : "localhost") + (publicPort != null ? ":" + publicPort : "")));
        return null;
    }).subscribeOn(SchedulerProviderFactory.getInstance().getSchedulerProvider().io()).subscribe(ret -> {
        ConsoleLogger.info("Container started.");
        sendTelemetry(true, null);
        operation.complete();
    }, e -> {
        e.printStackTrace();
        ConsoleLogger.error(e.getMessage());
        sendTelemetry(false, e.getMessage());
        EventUtil.logError(operation, ErrorType.systemError, new Exception(e), null, null);
        operation.complete();
    });
}
Also used : Path(java.nio.file.Path) DockerProgressHandler(com.microsoft.azuretools.container.DockerProgressHandler) Container(com.spotify.docker.client.messages.Container) DockerClient(com.spotify.docker.client.DockerClient) DefaultDockerClient(com.spotify.docker.client.DefaultDockerClient) FileNotFoundException(java.io.FileNotFoundException) PortMapping(com.spotify.docker.client.messages.Container.PortMapping) Operation(com.microsoft.azuretools.telemetrywrapper.Operation) PortMapping(com.spotify.docker.client.messages.Container.PortMapping) URI(java.net.URI) InvalidFormDataException(com.microsoft.azuretools.azurecommons.exceptions.InvalidFormDataException) FileNotFoundException(java.io.FileNotFoundException) DockerCertificateException(com.spotify.docker.client.exceptions.DockerCertificateException)

Example 3 with Operation

use of com.microsoft.azuretools.telemetrywrapper.Operation in project azure-tools-for-java by Microsoft.

the class SignInCommandHandler method call.

private static <T> T call(Callable<T> loginCallable, String authMethod) {
    final Operation operation = TelemetryManager.createOperation(ACCOUNT, SIGNIN);
    final Map<String, String> properties = new HashMap<>();
    properties.put(SIGNIN_METHOD, authMethod);
    try {
        operation.start();
        operation.trackProperties(properties);
        operation.trackProperty(AZURE_ENVIRONMENT, Azure.az(AzureCloud.class).getName());
        return loginCallable.call();
    } catch (Exception e) {
        if (shouldNoticeErrorToUser(e)) {
            EventUtil.logError(operation, ErrorType.userError, e, properties, null);
        }
        throw new AzureToolkitRuntimeException(e.getMessage(), e);
    } finally {
        operation.complete();
    }
}
Also used : HashMap(java.util.HashMap) AzureToolkitRuntimeException(com.microsoft.azure.toolkit.lib.common.exception.AzureToolkitRuntimeException) Operation(com.microsoft.azuretools.telemetrywrapper.Operation) AzureOperation(com.microsoft.azure.toolkit.lib.common.operation.AzureOperation) AzureString(com.microsoft.azure.toolkit.lib.common.bundle.AzureString) AzureExecutionException(com.microsoft.azure.toolkit.lib.common.exception.AzureExecutionException) MsalClientException(com.microsoft.aad.msal4j.MsalClientException) CancellationException(java.util.concurrent.CancellationException) AzureToolkitRuntimeException(com.microsoft.azure.toolkit.lib.common.exception.AzureToolkitRuntimeException) ExecutionException(org.eclipse.core.commands.ExecutionException)

Example 4 with Operation

use of com.microsoft.azuretools.telemetrywrapper.Operation in project azure-tools-for-java by Microsoft.

the class PublishWebAppOnLinuxDialog method execute.

private void execute() {
    Operation operation = TelemetryManager.createOperation(WEBAPP, DEPLOY_WEBAPP_CONTAINER);
    Observable.fromCallable(() -> {
        ConsoleLogger.info("Starting job ...  ");
        operation.start();
        if (basePath == null) {
            ConsoleLogger.error("Project base path is null.");
            throw new FileNotFoundException("Project base path is null.");
        }
        // locate artifact to specified location
        String targetFilePath = model.getTargetPath();
        ConsoleLogger.info(String.format("Locating artifact ... [%s]", targetFilePath));
        // validate dockerfile
        Path targetDockerfile = Paths.get(model.getDockerFilePath());
        ConsoleLogger.info(String.format("Validating dockerfile ... [%s]", targetDockerfile));
        if (!targetDockerfile.toFile().exists()) {
            throw new FileNotFoundException("Dockerfile not found.");
        }
        // replace placeholder if exists
        String content = new String(Files.readAllBytes(targetDockerfile));
        content = content.replaceAll(Constant.DOCKERFILE_ARTIFACT_PLACEHOLDER, Paths.get(basePath).toUri().relativize(Paths.get(targetFilePath).toUri()).getPath());
        Files.write(targetDockerfile, content.getBytes());
        // build image
        PrivateRegistryImageSetting acrInfo = model.getPrivateRegistryImageSetting();
        ConsoleLogger.info(String.format("Building image ...  [%s]", acrInfo.getImageTagWithServerUrl()));
        DockerClient docker = DefaultDockerClient.fromEnv().build();
        DockerUtil.ping(docker);
        DockerUtil.buildImage(docker, acrInfo.getImageTagWithServerUrl(), targetDockerfile.getParent(), targetDockerfile.getFileName().toString(), new DockerProgressHandler());
        // push to ACR
        ConsoleLogger.info(String.format("Pushing to ACR ... [%s] ", acrInfo.getServerUrl()));
        DockerUtil.pushImage(docker, acrInfo.getServerUrl(), acrInfo.getUsername(), acrInfo.getPassword(), acrInfo.getImageTagWithServerUrl(), new DockerProgressHandler());
        // deploy
        if (model.isCreatingNewWebAppOnLinux()) {
            // create new WebApp
            ConsoleLogger.info(String.format("Creating new WebApp ... [%s]", model.getWebAppName()));
            IWebApp app = AzureWebAppMvpModel.getInstance().createAzureWebAppWithPrivateRegistryImage(model);
            if (app != null && app.name() != null) {
                ConsoleLogger.info(String.format("URL:  http://%s.azurewebsites.net/", app.name()));
                AzureUIRefreshCore.execute(new AzureUIRefreshEvent(AzureUIRefreshEvent.EventType.REFRESH, null));
            }
        } else {
            // update WebApp
            ConsoleLogger.info(String.format("Updating WebApp ... [%s]", model.getWebAppName()));
            IWebApp app = AzureWebAppMvpModel.getInstance().updateWebAppOnDocker(model.getWebAppId(), acrInfo);
            if (app != null && app.name() != null) {
                ConsoleLogger.info(String.format("URL:  http://%s.azurewebsites.net/", app.name()));
            }
        }
        return null;
    }).subscribeOn(SchedulerProviderFactory.getInstance().getSchedulerProvider().io()).subscribe(ret -> {
        ConsoleLogger.info("Job done");
        if (model.isCreatingNewWebAppOnLinux() && AzureUIRefreshCore.listeners != null) {
            AzureUIRefreshCore.execute(new AzureUIRefreshEvent(AzureUIRefreshEvent.EventType.REFRESH, null));
        }
        sendTelemetry(true, null);
        operation.complete();
    }, err -> {
        err.printStackTrace();
        ConsoleLogger.error(err.getMessage());
        EventUtil.logError(operation, ErrorType.systemError, new Exception(err), null, null);
        operation.complete();
        sendTelemetry(false, err.getMessage());
    });
}
Also used : Path(java.nio.file.Path) PrivateRegistryImageSetting(com.microsoft.azuretools.core.mvp.model.webapp.PrivateRegistryImageSetting) DockerProgressHandler(com.microsoft.azuretools.container.DockerProgressHandler) DockerClient(com.spotify.docker.client.DockerClient) DefaultDockerClient(com.spotify.docker.client.DefaultDockerClient) FileNotFoundException(java.io.FileNotFoundException) Operation(com.microsoft.azuretools.telemetrywrapper.Operation) AzureUIRefreshEvent(com.microsoft.azuretools.utils.AzureUIRefreshEvent) InvalidFormDataException(com.microsoft.azuretools.azurecommons.exceptions.InvalidFormDataException) FileNotFoundException(java.io.FileNotFoundException) IWebApp(com.microsoft.azure.toolkit.lib.appservice.service.IWebApp)

Example 5 with Operation

use of com.microsoft.azuretools.telemetrywrapper.Operation in project azure-tools-for-java by Microsoft.

the class AzureSignInAction method onAzureSignIn.

public static void onAzureSignIn(Project project) {
    JFrame frame = WindowManager.getInstance().getFrame(project);
    AuthMethodManager authMethodManager = AuthMethodManager.getInstance();
    boolean isSignIn = authMethodManager.isSignedIn();
    if (isSignIn) {
        boolean res = DefaultLoader.getUIHelper().showYesNoDialog(frame.getRootPane(), getSignOutWarningMessage(authMethodManager), "Azure Sign Out", AzureIconLoader.loadIcon(AzureIconSymbol.Common.AZURE));
        if (res) {
            EventUtil.executeWithLog(ACCOUNT, SIGNOUT, (operation) -> {
                authMethodManager.signOut();
            });
        }
    } else {
        signInIfNotSignedIn(project).subscribe(isLoggedIn -> {
            if (isLoggedIn) {
                AzureAccount az = Azure.az(AzureAccount.class);
                AzureTaskManager.getInstance().runOnPooledThread(() -> authMethodManager.getAzureManager().getSelectedSubscriptions().stream().limit(5).forEach(s -> {
                    // pre-load regions;
                    az.listRegions(s.getId());
                }));
            }
        });
    }
}
Also used : AuthMethodManager(com.microsoft.azuretools.authmanage.AuthMethodManager) Azure(com.microsoft.azure.toolkit.lib.Azure) AzureBundle.message(com.microsoft.intellij.ui.messages.AzureBundle.message) DataKeys(com.intellij.openapi.actionSystem.DataKeys) ACCOUNT(com.microsoft.azuretools.telemetry.TelemetryConstants.ACCOUNT) StringUtils(org.apache.commons.lang3.StringUtils) IDeviceLoginUI(com.microsoft.azuretools.adauth.IDeviceLoginUI) DeviceLoginUI(com.microsoft.intellij.ui.DeviceLoginUI) AzureIconSymbol(com.microsoft.tooling.msservices.serviceexplorer.AzureIconSymbol) AzureCloud(com.microsoft.azure.toolkit.lib.auth.AzureCloud) Single(rx.Single) UIHelperImpl(com.microsoft.intellij.helpers.UIHelperImpl) Duration(java.time.Duration) Map(java.util.Map) AzureAnAction(com.microsoft.intellij.AzureAnAction) AzureString(com.microsoft.azure.toolkit.lib.common.bundle.AzureString) IdentityAzureManager(com.microsoft.azuretools.sdkmanage.IdentityAzureManager) AccountEntity(com.microsoft.azure.toolkit.lib.auth.model.AccountEntity) AZURE_ENVIRONMENT(com.microsoft.azuretools.telemetry.TelemetryConstants.AZURE_ENVIRONMENT) Logger(com.intellij.openapi.diagnostic.Logger) JFrame(javax.swing.JFrame) MsalClientException(com.microsoft.aad.msal4j.MsalClientException) AzureLoginHelper(com.microsoft.intellij.util.AzureLoginHelper) ProgressManager(com.intellij.openapi.progress.ProgressManager) CancellationException(java.util.concurrent.CancellationException) AuthMethod(com.microsoft.azuretools.authmanage.AuthMethod) WindowManager(com.intellij.openapi.wm.WindowManager) ErrorType(com.microsoft.azuretools.telemetrywrapper.ErrorType) Operation(com.microsoft.azuretools.telemetrywrapper.Operation) AuthConfiguration(com.microsoft.azure.toolkit.lib.auth.model.AuthConfiguration) SIGNIN_METHOD(com.microsoft.azuretools.telemetry.TelemetryConstants.SIGNIN_METHOD) Nullable(org.jetbrains.annotations.Nullable) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) SIGNIN(com.microsoft.azuretools.telemetry.TelemetryConstants.SIGNIN) AzureAccount(com.microsoft.azure.toolkit.lib.auth.AzureAccount) DeviceCodeAccount(com.microsoft.azure.toolkit.lib.auth.core.devicecode.DeviceCodeAccount) AnActionEvent(com.intellij.openapi.actionSystem.AnActionEvent) Optional(java.util.Optional) EventUtil(com.microsoft.azuretools.telemetrywrapper.EventUtil) Lombok(lombok.Lombok) NotNull(org.jetbrains.annotations.NotNull) AzureTaskManager(com.microsoft.azure.toolkit.lib.common.task.AzureTaskManager) AzureEnvironmentUtils(com.microsoft.azure.toolkit.lib.auth.util.AzureEnvironmentUtils) AzureOperation(com.microsoft.azure.toolkit.lib.common.operation.AzureOperation) AzureIconLoader(com.microsoft.intellij.helpers.AzureIconLoader) Exceptions(rx.exceptions.Exceptions) AzureOperationBundle(com.microsoft.azure.toolkit.lib.common.operation.AzureOperationBundle) SignInWindow(com.microsoft.intellij.ui.SignInWindow) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) CompletableFuture(java.util.concurrent.CompletableFuture) Supplier(java.util.function.Supplier) CollectionUtils(org.apache.commons.collections4.CollectionUtils) AzureTask(com.microsoft.azure.toolkit.lib.common.task.AzureTask) Project(com.intellij.openapi.project.Project) DefaultLoader(com.microsoft.tooling.msservices.components.DefaultLoader) Schedulers(reactor.core.scheduler.Schedulers) ServicePrincipalLoginDialog(com.microsoft.intellij.ui.ServicePrincipalLoginDialog) SIGNOUT(com.microsoft.azuretools.telemetry.TelemetryConstants.SIGNOUT) AuthMethodDetails(com.microsoft.azuretools.authmanage.models.AuthMethodDetails) AzureToolkitRuntimeException(com.microsoft.azure.toolkit.lib.common.exception.AzureToolkitRuntimeException) AzureMessager(com.microsoft.azure.toolkit.lib.common.messager.AzureMessager) Mono(reactor.core.publisher.Mono) ErrorWindow(com.microsoft.intellij.ui.ErrorWindow) Flux(reactor.core.publisher.Flux) TelemetryConstants(com.microsoft.azuretools.telemetry.TelemetryConstants) SignInOutAction(com.microsoft.intellij.serviceexplorer.azure.SignInOutAction) TelemetryManager(com.microsoft.azuretools.telemetrywrapper.TelemetryManager) AuthType(com.microsoft.azure.toolkit.lib.auth.model.AuthType) JFrame(javax.swing.JFrame) AzureAccount(com.microsoft.azure.toolkit.lib.auth.AzureAccount) AuthMethodManager(com.microsoft.azuretools.authmanage.AuthMethodManager)

Aggregations

Operation (com.microsoft.azuretools.telemetrywrapper.Operation)29 AzureOperation (com.microsoft.azure.toolkit.lib.common.operation.AzureOperation)9 IOException (java.io.IOException)8 File (java.io.File)7 HashMap (java.util.HashMap)7 AzureString (com.microsoft.azure.toolkit.lib.common.bundle.AzureString)6 EventUtil (com.microsoft.azuretools.telemetrywrapper.EventUtil)6 AzureToolkitRuntimeException (com.microsoft.azure.toolkit.lib.common.exception.AzureToolkitRuntimeException)5 TelemetryConstants (com.microsoft.azuretools.telemetry.TelemetryConstants)5 ErrorType (com.microsoft.azuretools.telemetrywrapper.ErrorType)5 Map (java.util.Map)5 Project (com.intellij.openapi.project.Project)4 MsalClientException (com.microsoft.aad.msal4j.MsalClientException)4 TelemetryManager (com.microsoft.azuretools.telemetrywrapper.TelemetryManager)4 DefaultDockerClient (com.spotify.docker.client.DefaultDockerClient)4 Path (java.nio.file.Path)4 CancellationException (java.util.concurrent.CancellationException)4 DefaultExecutionResult (com.intellij.execution.DefaultExecutionResult)3 ProgressIndicator (com.intellij.openapi.progress.ProgressIndicator)3 AzureTask (com.microsoft.azure.toolkit.lib.common.task.AzureTask)3