Search in sources :

Example 61 with NotNull

use of com.microsoft.azuretools.azurecommons.helpers.NotNull in project azure-tools-for-java by Microsoft.

the class JobUtils method deployArtifactToADLS.

// Have to catch IOException in subscribe
@NotNull
public static Observable<String> deployArtifactToADLS(@NotNull String artifactLocalPath, @NotNull String adlRootPath, @NotNull String accessToken) {
    return Observable.fromCallable(() -> {
        final File localFile = new File(artifactLocalPath);
        final URI remote = URI.create(adlRootPath).resolve("SparkSubmission/").resolve(getFormatPathByDate() + "/").resolve(localFile.getName());
        final ADLStoreClient storeClient = ADLStoreClient.createClient(remote.getHost(), accessToken);
        try (final OutputStream adlsOutputStream = storeClient.createFile(remote.getPath(), IfExists.OVERWRITE, "755", true)) {
            final long size = IOUtils.copyLarge(new FileInputStream(localFile), adlsOutputStream);
            adlsOutputStream.flush();
            adlsOutputStream.close();
            return remote.toString();
        }
    });
}
Also used : ADLStoreClient(com.microsoft.azure.datalake.store.ADLStoreClient) ClusterFileBase64BufferedOutputStream(com.microsoft.azure.hdinsight.sdk.io.spark.ClusterFileBase64BufferedOutputStream) Base64OutputStream(org.apache.commons.codec.binary.Base64OutputStream) URI(java.net.URI) NotNull(com.microsoft.azuretools.azurecommons.helpers.NotNull)

Example 62 with NotNull

use of com.microsoft.azuretools.azurecommons.helpers.NotNull in project azure-tools-for-java by Microsoft.

the class JobUtils method getInformationFromYarnLogDom.

private static String getInformationFromYarnLogDom(@NotNull WebClient client, @NotNull String baseUrl, @NotNull String type, long start, int size) {
    URI url = null;
    try {
        url = new URI(baseUrl + "/").resolve(String.format("%s?start=%d", type, start) + (size <= 0 ? "" : String.format("&&end=%d", start + size)));
        final HtmlPage htmlPage = client.getPage(url.toString());
        final Iterator<DomElement> iterator = htmlPage.getElementById("navcell").getNextElementSibling().getChildElements().iterator();
        final HashMap<String, String> logTypeMap = new HashMap<>();
        final AtomicReference<String> logType = new AtomicReference<>();
        String logs = "";
        while (iterator.hasNext()) {
            final DomElement node = iterator.next();
            if (node instanceof HtmlParagraph) {
                // In history server, need to read log type paragraph in page
                final Pattern logTypePattern = Pattern.compile("Log Type:\\s+(\\S+)");
                Optional.ofNullable(node.getFirstChild()).map(DomNode::getTextContent).map(String::trim).map(logTypePattern::matcher).filter(Matcher::matches).map(matcher -> matcher.group(1)).ifPresent(logType::set);
            } else if (node instanceof HtmlPreformattedText) {
                // In running, no log type paragraph in page
                logs = Optional.ofNullable(node.getFirstChild()).map(DomNode::getTextContent).orElse("");
                if (logType.get() != null) {
                    // Only get the first <pre>...</pre>
                    logTypeMap.put(logType.get(), logs);
                    logType.set(null);
                }
            }
        }
        return logTypeMap.getOrDefault(type, logs);
    } catch (final FailingHttpStatusCodeException httpError) {
        // the log is moving to job history server, just wait and retry.
        if (httpError.getStatusCode() != HttpStatus.SC_FORBIDDEN) {
            LOGGER.warn("The GET request to " + url + " responded error: " + httpError.getMessage());
        }
    } catch (final URISyntaxException e) {
        LOGGER.error("baseUrl has syntax error: " + baseUrl);
    } catch (final Exception e) {
        LOGGER.warn("get Spark job log Error", e);
    }
    return "";
}
Also used : TypeToken(com.google.gson.reflect.TypeToken) HDStorageAccount(com.microsoft.azure.hdinsight.sdk.storage.HDStorageAccount) URL(java.net.URL) URISyntaxException(java.net.URISyntaxException) LoggerFactory(org.slf4j.LoggerFactory) LivySession(com.microsoft.azure.hdinsight.spark.jobs.livy.LivySession) SparkSession(com.microsoft.azure.hdinsight.sdk.common.livy.interactive.SparkSession) RequestConfig(org.apache.http.client.config.RequestConfig) StringUtils(org.apache.commons.lang3.StringUtils) GsonBuilder(com.google.gson.GsonBuilder) AuthenticationException(com.microsoft.azure.hdinsight.sdk.common.AuthenticationException) HDInsightLoader(com.microsoft.azure.hdinsight.common.HDInsightLoader) Info(com.microsoft.azure.hdinsight.common.MessageInfoType.Info) WebHdfsParamsBuilder(com.microsoft.azure.hdinsight.sdk.storage.webhdfs.WebHdfsParamsBuilder) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) Single(rx.Single) Matcher(java.util.regex.Matcher) ClusterManagerEx(com.microsoft.azure.hdinsight.common.ClusterManagerEx) Gson(com.google.gson.Gson) Cache(com.gargoylesoftware.htmlunit.Cache) Schedulers(rx.schedulers.Schedulers) ClientStorageAccount(com.microsoft.tooling.msservices.model.storage.ClientStorageAccount) FailingHttpStatusCodeException(com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException) URI(java.net.URI) TOOL(com.microsoft.azure.hdinsight.spark.common.log.SparkLogLine.TOOL) ClusterFileBase64BufferedOutputStream(com.microsoft.azure.hdinsight.sdk.io.spark.ClusterFileBase64BufferedOutputStream) Nullable(com.microsoft.azuretools.azurecommons.helpers.Nullable) URIBuilder(org.apache.http.client.utils.URIBuilder) LivyBatchesInformation(com.microsoft.azure.hdinsight.spark.jobs.livy.LivyBatchesInformation) AUTHORIZATION(org.apache.http.HttpHeaders.AUTHORIZATION) Exceptions.propagate(rx.exceptions.Exceptions.propagate) ContentType(org.apache.http.entity.ContentType) Observer(rx.Observer) MessageInfoType(com.microsoft.azure.hdinsight.common.MessageInfoType) IOUtils(org.apache.commons.io.IOUtils) List(java.util.List) HttpGet(org.apache.http.client.methods.HttpGet) Type(java.lang.reflect.Type) Pattern(java.util.regex.Pattern) CredentialsProvider(org.apache.http.client.CredentialsProvider) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) Subscription(rx.Subscription) UnknownServiceException(java.net.UnknownServiceException) HttpClients(org.apache.http.impl.client.HttpClients) App(com.microsoft.azure.hdinsight.sdk.rest.yarn.rm.App) java.util(java.util) com.gargoylesoftware.htmlunit.html(com.gargoylesoftware.htmlunit.html) NotNull(com.microsoft.azuretools.azurecommons.helpers.NotNull) EmulatorClusterDetail(com.microsoft.azure.hdinsight.sdk.cluster.EmulatorClusterDetail) LivyCluster(com.microsoft.azure.hdinsight.sdk.cluster.LivyCluster) ADLStoreClient(com.microsoft.azure.datalake.store.ADLStoreClient) HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) SimpleImmutableEntry(java.util.AbstractMap.SimpleImmutableEntry) AtomicReference(java.util.concurrent.atomic.AtomicReference) Observable(rx.Observable) StringHelper(com.microsoft.azuretools.azurecommons.helpers.StringHelper) BrowserVersion(com.gargoylesoftware.htmlunit.BrowserVersion) HttpClient(org.apache.http.client.HttpClient) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) RequestBuilder(org.apache.http.client.methods.RequestBuilder) DefaultLoader(com.microsoft.tooling.msservices.components.DefaultLoader) Base64OutputStream(org.apache.commons.codec.binary.Base64OutputStream) IClusterDetail(com.microsoft.azure.hdinsight.sdk.cluster.IClusterDetail) SparkBatchSubmission(com.microsoft.azure.hdinsight.spark.common.SparkBatchSubmission) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) Logger(org.slf4j.Logger) MfaEspCluster(com.microsoft.azure.hdinsight.sdk.cluster.MfaEspCluster) SparkBatchEspMfaSubmission(com.microsoft.azure.hdinsight.spark.common.SparkBatchEspMfaSubmission) StorageClientSDKManager(com.microsoft.tooling.msservices.helpers.azure.sdk.StorageClientSDKManager) HDIException(com.microsoft.azure.hdinsight.sdk.common.HDIException) org.apache.http(org.apache.http) HttpObservable(com.microsoft.azure.hdinsight.sdk.common.HttpObservable) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) java.awt(java.awt) ExecutionException(java.util.concurrent.ExecutionException) IfExists(com.microsoft.azure.datalake.store.IfExists) BlobContainer(com.microsoft.tooling.msservices.model.storage.BlobContainer) java.io(java.io) ApplicationMasterLogs(com.microsoft.azure.hdinsight.sdk.rest.yarn.rm.ApplicationMasterLogs) AzureCmdException(com.microsoft.azuretools.azurecommons.helpers.AzureCmdException) AuthScope(org.apache.http.auth.AuthScope) StreamUtil(com.microsoft.azure.hdinsight.common.StreamUtil) CallableSingleArg(com.microsoft.tooling.msservices.helpers.CallableSingleArg) WebClient(com.gargoylesoftware.htmlunit.WebClient) StorageAccountType(com.microsoft.azure.hdinsight.sdk.storage.StorageAccountType) HttpExchange(com.sun.net.httpserver.HttpExchange) InputStreamEntity(org.apache.http.entity.InputStreamEntity) SparkLogLine(com.microsoft.azure.hdinsight.spark.common.log.SparkLogLine) IHDIStorageAccount(com.microsoft.azure.hdinsight.sdk.storage.IHDIStorageAccount) com.jcraft.jsch(com.jcraft.jsch) Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) AtomicReference(java.util.concurrent.atomic.AtomicReference) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) URISyntaxException(java.net.URISyntaxException) AuthenticationException(com.microsoft.azure.hdinsight.sdk.common.AuthenticationException) FailingHttpStatusCodeException(com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException) UnknownServiceException(java.net.UnknownServiceException) HDIException(com.microsoft.azure.hdinsight.sdk.common.HDIException) ExecutionException(java.util.concurrent.ExecutionException) AzureCmdException(com.microsoft.azuretools.azurecommons.helpers.AzureCmdException) FailingHttpStatusCodeException(com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException)

Example 63 with NotNull

use of com.microsoft.azuretools.azurecommons.helpers.NotNull in project azure-tools-for-java by Microsoft.

the class SparkRestUtil method getSparkApplications.

@NotNull
public static List<Application> getSparkApplications(@NotNull IClusterDetail clusterDetail) throws HDIException, IOException {
    HttpEntity entity = getSparkRestEntity(clusterDetail, "");
    Optional<List<Application>> apps = ObjectConvertUtils.convertEntityToList(entity, Application.class);
    // spark job has at least one attempt
    return apps.orElse(RestUtil.getEmptyList(Application.class)).stream().filter(app -> app.getAttempts().size() != 0 && app.getAttempts().get(0).getAttemptId() != null).collect(Collectors.toList());
}
Also used : java.util(java.util) Application(com.microsoft.azure.hdinsight.sdk.rest.spark.Application) NotNull(com.microsoft.azuretools.azurecommons.helpers.NotNull) Task(com.microsoft.azure.hdinsight.sdk.rest.spark.task.Task) ObjectConvertUtils(com.microsoft.azure.hdinsight.sdk.rest.ObjectConvertUtils) HDInsightLoader(com.microsoft.azure.hdinsight.common.HDInsightLoader) JSONObject(org.json.JSONObject) Charset(java.nio.charset.Charset) ZipFile(java.util.zip.ZipFile) JobStartEventLog(com.microsoft.azure.hdinsight.sdk.rest.spark.event.JobStartEventLog) AttemptWithAppId(com.microsoft.azure.hdinsight.sdk.rest.AttemptWithAppId) ZipEntry(java.util.zip.ZipEntry) IClusterDetail(com.microsoft.azure.hdinsight.sdk.cluster.IClusterDetail) HDIException(com.microsoft.azure.hdinsight.sdk.common.HDIException) HttpEntity(org.apache.http.HttpEntity) Executor(com.microsoft.azure.hdinsight.sdk.rest.spark.executor.Executor) FileUtils(org.apache.commons.io.FileUtils) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) File(java.io.File) ExecutionException(java.util.concurrent.ExecutionException) IOUtils(org.apache.commons.io.IOUtils) Job(com.microsoft.azure.hdinsight.sdk.rest.spark.job.Job) Stage(com.microsoft.azure.hdinsight.sdk.rest.spark.stage.Stage) RestUtil(com.microsoft.azure.hdinsight.sdk.rest.RestUtil) InputStream(java.io.InputStream) HttpEntity(org.apache.http.HttpEntity) NotNull(com.microsoft.azuretools.azurecommons.helpers.NotNull)

Example 64 with NotNull

use of com.microsoft.azuretools.azurecommons.helpers.NotNull in project azure-tools-for-java by Microsoft.

the class SparkRestUtil method getSparkEventLogs.

public static List<JobStartEventLog> getSparkEventLogs(@NotNull ApplicationKey key) throws HDIException, IOException {
    String url = String.format("%s/logs", key.getAppId());
    String eventLogsPath = String.format("%s/SparkEventLogs/%s/eventLogs.zip", HDInsightLoader.getHDInsightHelper().getPluginRootPath(), key.getAppId());
    File file = new File(eventLogsPath);
    HttpEntity entity = getSparkRestEntity(key.getClusterDetails(), url);
    InputStream inputStream = entity.getContent();
    FileUtils.copyInputStreamToFile(inputStream, file);
    IOUtils.closeQuietly(inputStream);
    ZipFile zipFile = new ZipFile(file);
    List<? extends ZipEntry> entities = Collections.list(zipFile.entries());
    // every application has an attempt in event log
    // and the entity name should be in formation "{appId}_{attemptId}"
    String entityName = String.format("%s_%s", key.getAppId(), entities.size());
    ZipEntry lastEntity = zipFile.getEntry(entityName);
    if (lastEntity == null) {
        throw new HDIException(String.format("No Spark event log entity found for app: %s", key.getAppId()));
    }
    InputStream zipFileInputStream = zipFile.getInputStream(lastEntity);
    String entityContent = IOUtils.toString(zipFileInputStream, Charset.forName("utf-8"));
    String[] lines = entityContent.split("\n");
    List<JobStartEventLog> jobStartEvents = Arrays.stream(lines).filter(line -> {
        JSONObject jsonObject = new JSONObject(line);
        String eventName = jsonObject.getString("Event");
        return eventName.equalsIgnoreCase("SparkListenerJobStart");
    }).map(oneLine -> ObjectConvertUtils.convertToObjectQuietly(oneLine, JobStartEventLog.class)).filter(Objects::nonNull).collect(Collectors.toList());
    return jobStartEvents;
}
Also used : java.util(java.util) Application(com.microsoft.azure.hdinsight.sdk.rest.spark.Application) NotNull(com.microsoft.azuretools.azurecommons.helpers.NotNull) Task(com.microsoft.azure.hdinsight.sdk.rest.spark.task.Task) ObjectConvertUtils(com.microsoft.azure.hdinsight.sdk.rest.ObjectConvertUtils) HDInsightLoader(com.microsoft.azure.hdinsight.common.HDInsightLoader) JSONObject(org.json.JSONObject) Charset(java.nio.charset.Charset) ZipFile(java.util.zip.ZipFile) JobStartEventLog(com.microsoft.azure.hdinsight.sdk.rest.spark.event.JobStartEventLog) AttemptWithAppId(com.microsoft.azure.hdinsight.sdk.rest.AttemptWithAppId) ZipEntry(java.util.zip.ZipEntry) IClusterDetail(com.microsoft.azure.hdinsight.sdk.cluster.IClusterDetail) HDIException(com.microsoft.azure.hdinsight.sdk.common.HDIException) HttpEntity(org.apache.http.HttpEntity) Executor(com.microsoft.azure.hdinsight.sdk.rest.spark.executor.Executor) FileUtils(org.apache.commons.io.FileUtils) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) File(java.io.File) ExecutionException(java.util.concurrent.ExecutionException) IOUtils(org.apache.commons.io.IOUtils) Job(com.microsoft.azure.hdinsight.sdk.rest.spark.job.Job) Stage(com.microsoft.azure.hdinsight.sdk.rest.spark.stage.Stage) RestUtil(com.microsoft.azure.hdinsight.sdk.rest.RestUtil) InputStream(java.io.InputStream) HttpEntity(org.apache.http.HttpEntity) InputStream(java.io.InputStream) ZipEntry(java.util.zip.ZipEntry) HDIException(com.microsoft.azure.hdinsight.sdk.common.HDIException) ZipFile(java.util.zip.ZipFile) JSONObject(org.json.JSONObject) JobStartEventLog(com.microsoft.azure.hdinsight.sdk.rest.spark.event.JobStartEventLog) ZipFile(java.util.zip.ZipFile) File(java.io.File)

Example 65 with NotNull

use of com.microsoft.azuretools.azurecommons.helpers.NotNull in project azure-tools-for-java by Microsoft.

the class ClusterOperationImpl method requestWithToken.

@NotNull
public <T> T requestWithToken(@NotNull String tenantId, @NotNull final RequestCallback<T> requestCallback) throws Throwable {
    AzureManager azureManager = AuthMethodManager.getInstance().getAzureManager();
    // not signed in
    if (azureManager == null) {
        return null;
    }
    String accessToken = azureManager.getAccessToken(tenantId);
    return requestCallback.execute(accessToken);
}
Also used : AzureManager(com.microsoft.azuretools.sdkmanage.AzureManager) NotNull(com.microsoft.azuretools.azurecommons.helpers.NotNull)

Aggregations

NotNull (com.microsoft.azuretools.azurecommons.helpers.NotNull)65 AzureCmdException (com.microsoft.azuretools.azurecommons.helpers.AzureCmdException)21 Nullable (com.microsoft.azuretools.azurecommons.helpers.Nullable)8 File (java.io.File)8 IOException (java.io.IOException)8 IClusterDetail (com.microsoft.azure.hdinsight.sdk.cluster.IClusterDetail)7 java.util (java.util)7 Observable (rx.Observable)7 URI (java.net.URI)6 HDIException (com.microsoft.azure.hdinsight.sdk.common.HDIException)5 ObjectConvertUtils (com.microsoft.azure.hdinsight.sdk.rest.ObjectConvertUtils)5 List (java.util.List)5 StringUtils (org.apache.commons.lang3.StringUtils)5 Project (com.intellij.openapi.project.Project)4 CloudQueue (com.microsoft.azure.storage.queue.CloudQueue)4 CloudQueueClient (com.microsoft.azure.storage.queue.CloudQueueClient)4 ExecutionException (java.util.concurrent.ExecutionException)4 Collectors (java.util.stream.Collectors)4 ExecutionException (com.intellij.execution.ExecutionException)3 Artifact (com.intellij.packaging.artifacts.Artifact)3