Search in sources :

Example 21 with Operation

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

the class CreateMySQLAction method createMySQL.

@AzureOperation(name = "mysql|server.create.task", params = { "config.getServerName()", "config.getSubscription().getName()" }, type = AzureOperation.Type.SERVICE)
public void createMySQL(final AzureMySQLConfig config) {
    final Operation operation = TelemetryManager.createOperation(ActionConstants.MySQL.CREATE);
    try {
        operation.start();
        final String subscriptionId = config.getSubscription().getId();
        EventUtil.logEvent(EventType.info, operation, Collections.singletonMap(TelemetryConstants.SUBSCRIPTIONID, subscriptionId));
        // create resource group if necessary.
        if (config.getResourceGroup() instanceof Draft) {
            try {
                Azure.az(AzureGroup.class).get(subscriptionId, config.getResourceGroup().getName());
            } catch (Throwable ex) {
                Azure.az(AzureGroup.class).subscription(subscriptionId).create(config.getResourceGroup().getName(), config.getRegion().getName());
            }
            config.setResourceGroup(Azure.az(AzureGroup.class).get(subscriptionId, config.getResourceGroup().getName()));
        }
        // create mysql server
        final MySqlServer server = Azure.az(AzureMySql.class).subscription(subscriptionId).create(MySqlServerConfig.builder().subscription(config.getSubscription()).resourceGroup(config.getResourceGroup()).region(config.getRegion()).name(config.getServerName()).version(config.getVersion()).administratorLoginName(config.getAdminUsername()).administratorLoginPassword(String.valueOf(config.getPassword())).build()).commit();
        // update access from azure services
        if (config.isAllowAccessFromAzureServices()) {
            server.firewallRules().enableAzureAccessRule();
        }
        // update access from local machine
        if (config.isAllowAccessFromLocalMachine()) {
            server.firewallRules().enableLocalMachineAccessRule(server.getPublicIpForLocalMachine());
        }
    } catch (final RuntimeException e) {
        EventUtil.logError(operation, ErrorType.systemError, e, null, null);
        throw e;
    } finally {
        operation.complete();
    }
}
Also used : Draft(com.microsoft.azure.toolkit.intellij.common.Draft) AzureMySql(com.microsoft.azure.toolkit.lib.mysql.AzureMySql) MySqlServer(com.microsoft.azure.toolkit.lib.mysql.MySqlServer) AzureGroup(com.microsoft.azure.toolkit.lib.resource.AzureGroup) AzureOperation(com.microsoft.azure.toolkit.lib.common.operation.AzureOperation) Operation(com.microsoft.azuretools.telemetrywrapper.Operation) AzureOperation(com.microsoft.azure.toolkit.lib.common.operation.AzureOperation)

Example 22 with Operation

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

the class SignInCommandHandler method onAzureSignIn.

private void onAzureSignIn(Shell shell) {
    final AuthMethodManager authMethodManager = AuthMethodManager.getInstance();
    boolean isSignIn = authMethodManager.isSignedIn();
    if (isSignIn) {
        boolean res = showYesNoDialog(shell, "Azure Sign Out", SignOutCommandHandler.getSignOutWarningMessage(authMethodManager));
        if (res) {
            EventUtil.executeWithLog(ACCOUNT, SIGNOUT, (operation) -> {
                authMethodManager.signOut();
            });
        }
    } else {
        signInIfNotSignedIn(shell).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) AzureExecutionException(com.microsoft.azure.toolkit.lib.common.exception.AzureExecutionException) IWorkbenchWindow(org.eclipse.ui.IWorkbenchWindow) StringUtils(org.apache.commons.lang3.StringUtils) IDeviceLoginUI(com.microsoft.azuretools.adauth.IDeviceLoginUI) AzureCloud(com.microsoft.azure.toolkit.lib.auth.AzureCloud) Single(rx.Single) PluginUtil(com.microsoft.azuretools.core.utils.PluginUtil) Duration(java.time.Duration) Map(java.util.Map) AzureString(com.microsoft.azure.toolkit.lib.common.bundle.AzureString) IdentityAzureManager(com.microsoft.azuretools.sdkmanage.IdentityAzureManager) AccountEntity(com.microsoft.azure.toolkit.lib.auth.model.AccountEntity) MsalClientException(com.microsoft.aad.msal4j.MsalClientException) CancellationException(java.util.concurrent.CancellationException) AuthMethod(com.microsoft.azuretools.authmanage.AuthMethod) ErrorType(com.microsoft.azuretools.telemetrywrapper.ErrorType) Operation(com.microsoft.azuretools.telemetrywrapper.Operation) AuthConfiguration(com.microsoft.azure.toolkit.lib.auth.model.AuthConfiguration) AzureTaskContext(com.microsoft.azure.toolkit.lib.common.task.AzureTaskContext) Window(org.eclipse.jface.window.Window) List(java.util.List) AzureAccount(com.microsoft.azure.toolkit.lib.auth.AzureAccount) DeviceCodeAccount(com.microsoft.azure.toolkit.lib.auth.core.devicecode.DeviceCodeAccount) SWT(org.eclipse.swt.SWT) DeviceLoginWindow(com.microsoft.azuretools.core.ui.DeviceLoginWindow) EventUtil(com.microsoft.azuretools.telemetrywrapper.EventUtil) Lombok(lombok.Lombok) AzureTaskManager(com.microsoft.azure.toolkit.lib.common.task.AzureTaskManager) SignInDialog(com.microsoft.azuretools.core.ui.SignInDialog) ExecutionEvent(org.eclipse.core.commands.ExecutionEvent) AzureAbstractHandler(com.microsoft.azuretools.core.utils.AzureAbstractHandler) AzureEnvironmentUtils(com.microsoft.azure.toolkit.lib.auth.util.AzureEnvironmentUtils) AzureOperation(com.microsoft.azure.toolkit.lib.common.operation.AzureOperation) Exceptions(rx.exceptions.Exceptions) AzureOperationBundle(com.microsoft.azure.toolkit.lib.common.operation.AzureOperationBundle) 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) HandlerUtil(org.eclipse.ui.handlers.HandlerUtil) ServicePrincipalLoginDialog(com.microsoft.azuretools.core.ui.ServicePrincipalLoginDialog) ErrorWindow(com.microsoft.azuretools.core.ui.ErrorWindow) Schedulers(reactor.core.scheduler.Schedulers) AuthMethodDetails(com.microsoft.azuretools.authmanage.models.AuthMethodDetails) Subscription(com.microsoft.azure.toolkit.lib.common.model.Subscription) AzureToolkitRuntimeException(com.microsoft.azure.toolkit.lib.common.exception.AzureToolkitRuntimeException) AzureMessager(com.microsoft.azure.toolkit.lib.common.messager.AzureMessager) Shell(org.eclipse.swt.widgets.Shell) Mono(reactor.core.publisher.Mono) ExecutionException(org.eclipse.core.commands.ExecutionException) Flux(reactor.core.publisher.Flux) TelemetryConstants(com.microsoft.azuretools.telemetry.TelemetryConstants) TelemetryManager(com.microsoft.azuretools.telemetrywrapper.TelemetryManager) MessageBox(org.eclipse.swt.widgets.MessageBox) AuthType(com.microsoft.azure.toolkit.lib.auth.model.AuthType) AzureAccount(com.microsoft.azure.toolkit.lib.auth.AzureAccount) AuthMethodManager(com.microsoft.azuretools.authmanage.AuthMethodManager)

Example 23 with Operation

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

the class CreateStorageAccountTask method execute.

public StorageAccount execute() {
    final Operation operation = TelemetryManager.createOperation(ActionConstants.StorageAccount.CREATE);
    try {
        operation.start();
        final String subscriptionId = config.getSubscription().getId();
        EventUtil.logEvent(EventType.info, operation, Collections.singletonMap(TelemetryConstants.SUBSCRIPTIONID, subscriptionId));
        // create resource group if necessary.
        new CreateResourceGroupTask(subscriptionId, config.getResourceGroup().getName(), config.getRegion()).execute();
        // create storage account
        return Azure.az(AzureStorageAccount.class).create(config).commit();
    } catch (final RuntimeException e) {
        EventUtil.logError(operation, ErrorType.systemError, e, null, null);
        throw e;
    } finally {
        operation.complete();
    }
}
Also used : CreateResourceGroupTask(com.microsoft.azure.toolkit.lib.resource.task.CreateResourceGroupTask) Operation(com.microsoft.azuretools.telemetrywrapper.Operation)

Example 24 with Operation

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

the class PushImageDialog method execute.

private void execute() {
    Operation operation = TelemetryManager.createOperation(ACR, ACR_PUSHIMAGE);
    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());
        return null;
    }).subscribeOn(SchedulerProviderFactory.getInstance().getSchedulerProvider().io()).subscribe(props -> {
        ConsoleLogger.info("pushed.");
        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) InvalidFormDataException(com.microsoft.azuretools.azurecommons.exceptions.InvalidFormDataException) FileNotFoundException(java.io.FileNotFoundException)

Example 25 with Operation

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

the class WebAppDeployDialog method deploy.

private void deploy(String artifactName, String artifactPath) {
    int selectedRow = table.getSelectionIndex();
    String appServiceName = table.getItems()[selectedRow].getText(0);
    IWebApp webApp = webAppDetailsMap.get(appServiceName);
    String jobDescription = String.format("Web App '%s' deployment", webApp.name());
    if (isDeployToSlot) {
        jobDescription = String.format("Web App '%s' deploy to slot '%s'", webApp.name(), isCreateNewSlot ? webAppSettingModel.getNewSlotName() : webAppSettingModel.getSlotName());
    }
    String deploymentName = UUID.randomUUID().toString();
    AzureDeploymentProgressNotification.createAzureDeploymentProgressNotification(deploymentName, jobDescription);
    boolean isDeployToRoot = btnDeployToRoot.getSelection();
    Job job = new Job(jobDescription) {

        @Override
        protected IStatus run(IProgressMonitor monitor) {
            String message = "Packaging Artifact...";
            String cancelMessage = "Interrupted by user";
            String successMessage = "";
            String errorMessage = "Error";
            Map<String, String> postEventProperties = new HashMap<>();
            try {
                boolean isJar = MavenUtils.isMavenProject(project) && MavenUtils.getPackaging(project).equals("jar");
                postEventProperties.put(TelemetryConstants.JAVA_APPNAME, project.getName());
                postEventProperties.put(TelemetryConstants.FILETYPE, isJar ? "jar" : "war");
                Runtime runtime = webApp.getRuntime();
                String osValue = (String) Optional.ofNullable(runtime.getOperatingSystem()).map(com.microsoft.azure.toolkit.lib.appservice.model.OperatingSystem::toString).orElse("");
                String webContainerValue = (String) Optional.ofNullable(runtime.getWebContainer()).map(WebContainer::getValue).orElse("");
                String javaVersionValue = (String) Optional.ofNullable(runtime.getJavaVersion()).map(com.microsoft.azure.toolkit.lib.appservice.model.JavaVersion::getValue).orElse("");
                postEventProperties.put(TelemetryConstants.RUNTIME, String.format("%s-%s-%s", osValue, webContainerValue, javaVersionValue));
                postEventProperties.put(TelemetryConstants.WEBAPP_DEPLOY_TO_SLOT, Boolean.valueOf(isDeployToSlot).toString());
            } catch (Exception e) {
            }
            String errTitle = "Deploy Web App Error";
            monitor.beginTask(message, IProgressMonitor.UNKNOWN);
            IWebAppBase<? extends AppServiceBaseEntity> deployTarget = null;
            Operation operation = TelemetryManager.createOperation(WEBAPP, DEPLOY_WEBAPP);
            try {
                operation.start();
                deployTarget = getRealWebApp(webApp, this, monitor, deploymentName);
                String sitePath = buildSiteLink(deployTarget, isDeployToRoot ? null : artifactName);
                AzureDeploymentProgressNotification.notifyProgress(this, deploymentName, sitePath, 5, message);
                if (!MavenUtils.isMavenProject(project)) {
                    export(artifactName, artifactPath);
                }
                message = "Deploying Web App...";
                if (isDeployToSlot) {
                    message = "Deploying Web App to Slot...";
                }
                monitor.setTaskName(message);
                AzureDeploymentProgressNotification.notifyProgress(this, deploymentName, sitePath, 30, message);
                AzureWebAppMvpModel.getInstance().deployArtifactsToWebApp(deployTarget, new File(artifactPath), isDeployToRoot, new UpdateProgressIndicator(monitor));
                if (monitor.isCanceled()) {
                    AzureDeploymentProgressNotification.notifyProgress(this, deploymentName, null, -1, cancelMessage);
                    return Status.CANCEL_STATUS;
                }
                message = "Checking Web App availability...";
                monitor.setTaskName(message);
                AzureDeploymentProgressNotification.notifyProgress(this, deploymentName, sitePath, 20, message);
                // to make warn up cancelable
                int stepLimit = 5;
                int sleepMs = 1000;
                CountDownLatch countDownLatch = new CountDownLatch(1);
                new Thread(() -> {
                    try {
                        for (int step = 0; step < stepLimit; ++step) {
                            if (monitor.isCanceled() || isUrlAccessible(sitePath)) {
                                // warm up
                                break;
                            }
                            Thread.sleep(sleepMs);
                        }
                    } catch (Exception ex) {
                        LOG.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "run@Thread@run@ProgressDialog@deploy@AppServiceCreateDialog@SingInDialog", ex));
                    } finally {
                        countDownLatch.countDown();
                    }
                }).start();
                try {
                    countDownLatch.await();
                } catch (Exception ignore) {
                }
                if (monitor.isCanceled()) {
                    // it's published but not warmed up yet - consider as success
                    AzureDeploymentProgressNotification.notifyProgress(this, deploymentName, sitePath, 100, successMessage);
                    return Status.CANCEL_STATUS;
                }
                monitor.done();
                AzureDeploymentProgressNotification.notifyProgress(this, deploymentName, sitePath, 100, successMessage);
                AppInsightsClient.create("Deploy as WebApp", "", postEventProperties);
            } catch (Exception ex) {
                postEventProperties.put("PublishError", ex.getMessage());
                LOG.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "run@ProgressDialog@deploy@AppServiceCreateDialog", ex));
                AzureDeploymentProgressNotification.notifyProgress(this, deploymentName, null, -1, errorMessage);
                if (deployTarget != null) {
                    deployTarget.start();
                }
                Display.getDefault().asyncExec(() -> ErrorWindow.go(parentShell, ex.getMessage(), errTitle));
                EventUtil.logError(operation, ErrorType.systemError, ex, postEventProperties, null);
            } finally {
                EventUtil.logEvent(EventType.info, operation, postEventProperties);
                operation.complete();
            }
            return Status.OK_STATUS;
        }
    };
    job.schedule();
}
Also used : Status(org.eclipse.core.runtime.Status) IStatus(org.eclipse.core.runtime.IStatus) HashMap(java.util.HashMap) WebContainer(com.microsoft.azure.toolkit.lib.appservice.model.WebContainer) Operation(com.microsoft.azuretools.telemetrywrapper.Operation) JavaVersion(com.microsoft.azure.toolkit.lib.appservice.model.JavaVersion) CountDownLatch(java.util.concurrent.CountDownLatch) Point(org.eclipse.swt.graphics.Point) IOException(java.io.IOException) IWebApp(com.microsoft.azure.toolkit.lib.appservice.service.IWebApp) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) Runtime(com.microsoft.azure.toolkit.lib.appservice.model.Runtime) UpdateProgressIndicator(com.microsoft.azuretools.core.utils.UpdateProgressIndicator) Job(org.eclipse.core.runtime.jobs.Job) File(java.io.File)

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