rightsStr = new ArrayList<>();
- for (com.microsoft.azure.management.eventhub.AccessRights rights : resource.rights()) {
+ for (AccessRights rights : resource.rights()) {
rightsStr.add(rights.toString());
}
info.append("\n\tRights: ").append(rightsStr);
@@ -2799,93 +3017,6 @@ public static void print(EventHubConsumerGroup resource) {
System.out.println(info.toString());
}
- /**
- * Print Batch AI Cluster.
- *
- * @param resource batch ai cluster
- */
- public static void print(BatchAICluster resource) {
- StringBuilder info = new StringBuilder("Batch AI cluster: ")
- .append("\n\tId: ").append(resource.id())
- .append("\n\tName: ").append(resource.name())
- .append("\n\tResource group: ").append(resource.workspace().resourceGroupName())
- .append("\n\tRegion: ").append(resource.workspace().regionName())
- .append("\n\tVM Size: ").append(resource.vmSize())
- .append("\n\tVM Priority: ").append(resource.vmPriority())
- .append("\n\tSubnet: ").append(resource.subnet())
- .append("\n\tAllocation state: ").append(resource.allocationState())
- .append("\n\tAllocation state transition time: ").append(resource.allocationStateTransitionTime())
- .append("\n\tCreation time: ").append(resource.creationTime())
- .append("\n\tCurrent node count: ").append(resource.currentNodeCount())
- .append("\n\tAllocation state transition time: ").append(resource.allocationStateTransitionTime())
- .append("\n\tAllocation state transition time: ").append(resource.allocationStateTransitionTime());
- if (resource.scaleSettings().autoScale() != null) {
- info.append("\n\tAuto scale settings: ")
- .append("\n\t\tInitial node count: ").append(resource.scaleSettings().autoScale().initialNodeCount())
- .append("\n\t\tMinimum node count: ").append(resource.scaleSettings().autoScale().minimumNodeCount())
- .append("\n\t\tMaximum node count: ").append(resource.scaleSettings().autoScale().maximumNodeCount());
- }
- if (resource.scaleSettings().manual() != null) {
- info.append("\n\tManual scale settings: ")
- .append("\n\t\tTarget node count: ").append(resource.scaleSettings().manual().targetNodeCount())
- .append("\n\t\tDeallocation option: ")
- .append(resource.scaleSettings().manual().nodeDeallocationOption());
- }
- if (resource.nodeStateCounts() != null) {
- info.append("\n\tNode state counts: ")
- .append("\n\t\tRunning nodes count: ").append(resource.nodeStateCounts().runningNodeCount())
- .append("\n\t\tIdle nodes count: ").append(resource.nodeStateCounts().idleNodeCount())
- .append("\n\t\tPreparing nodes count: ").append(resource.nodeStateCounts().preparingNodeCount())
- .append("\n\t\tLeaving nodes count: ").append(resource.nodeStateCounts().leavingNodeCount())
- .append("\n\t\tPreparing nodes count: ").append(resource.nodeStateCounts().preparingNodeCount());
- }
- if (resource.virtualMachineConfiguration() != null && resource.virtualMachineConfiguration().imageReference() != null) {
- info.append("\n\tVirtual machine configuration: ")
- .append("\n\t\tPublisher: ").append(resource.virtualMachineConfiguration().imageReference().publisher())
- .append("\n\t\tOffer: ").append(resource.virtualMachineConfiguration().imageReference().offer())
- .append("\n\t\tSku: ").append(resource.virtualMachineConfiguration().imageReference().sku())
- .append("\n\t\tVersion: ").append(resource.virtualMachineConfiguration().imageReference().version());
- }
- if (resource.nodeSetup() != null && resource.nodeSetup().setupTask() != null) {
- info.append("\n\tSetup task: ")
- .append("\n\t\tCommand line: ").append(resource.nodeSetup().setupTask().commandLine())
- .append("\n\t\tStdout/err Path Prefix: ").append(resource.nodeSetup().setupTask().stdOutErrPathPrefix());
- }
- System.out.println(info.toString());
- }
-
- /**
- * Print Batch AI Job.
- *
- * @param resource batch ai job
- */
- public static void print(BatchAIJob resource) {
- StringBuilder info = new StringBuilder("Batch AI job: ")
- .append("\n\tId: ").append(resource.id())
- .append("\n\tName: ").append(resource.name())
- .append("\n\tCluster Id: ").append(resource.cluster())
- .append("\n\tCreation time: ").append(resource.creationTime())
- .append("\n\tNode count: ").append(resource.nodeCount())
- .append("\n\tPriority: ").append(resource.schedulingPriority())
- .append("\n\tExecution state: ").append(resource.executionState())
- .append("\n\tExecution state transition time: ").append(resource.executionStateTransitionTime())
- .append("\n\tTool type: ").append(resource.toolType())
- .append("\n\tExperiment name: ").append(resource.experiment().name());
- if (resource.mountVolumes() != null) {
- info.append("\n\tMount volumes:");
- if (resource.mountVolumes().azureFileShares() != null) {
- info.append("\n\t\tAzure fileshares:");
- for (AzureFileShareReference share : resource.mountVolumes().azureFileShares()) {
- info.append("\n\t\t\tAccount name:").append(share.accountName())
- .append("\n\t\t\tFile Url:").append(share.azureFileUrl())
- .append("\n\t\t\tDirectory mode:").append(share.directoryMode())
- .append("\n\t\t\tFile mode:").append(share.fileMode())
- .append("\n\t\t\tRelative mount path:").append(share.relativeMountPath());
- }
- }
- }
- System.out.println(info.toString());
- }
/**
* Print Diagnostic Setting.
@@ -3125,32 +3256,209 @@ public static void print(MetricAlert metricAlert) {
}
System.out.println(info.toString());
}
- private static OkHttpClient httpClient;
/**
- * Ensure the HTTP client is valid.
+ * Print spring service settings.
+ *
+ * @param springService spring service instance
+ */
+ public static void print(SpringService springService) {
+ StringBuilder info = new StringBuilder("Spring Service: ")
+ .append("\n\tId: ").append(springService.id())
+ .append("\n\tName: ").append(springService.name())
+ .append("\n\tResource Group: ").append(springService.resourceGroupName())
+ .append("\n\tRegion: ").append(springService.region())
+ .append("\n\tTags: ").append(springService.tags());
+
+ ConfigServerProperties serverProperties = springService.getServerProperties();
+ if (serverProperties != null && serverProperties.provisioningState() != null
+ && serverProperties.provisioningState().equals(ConfigServerState.SUCCEEDED) && serverProperties.configServer() != null) {
+ info.append("\n\tProperties: ");
+ if (serverProperties.configServer().gitProperty() != null) {
+ info.append("\n\t\tGit: ").append(serverProperties.configServer().gitProperty().uri());
+ }
+ }
+
+ if (springService.sku() != null) {
+ info.append("\n\tSku: ")
+ .append("\n\t\tName: ").append(springService.sku().name())
+ .append("\n\t\tTier: ").append(springService.sku().tier())
+ .append("\n\t\tCapacity: ").append(springService.sku().capacity());
+ }
+
+ MonitoringSettingProperties monitoringSettingProperties = springService.getMonitoringSetting();
+ if (monitoringSettingProperties != null && monitoringSettingProperties.provisioningState() != null
+ && monitoringSettingProperties.provisioningState().equals(MonitoringSettingState.SUCCEEDED)) {
+ info.append("\n\tTrace: ")
+ .append("\n\t\tEnabled: ").append(monitoringSettingProperties.traceEnabled())
+ .append("\n\t\tApp Insight Instrumentation Key: ").append(monitoringSettingProperties.appInsightsInstrumentationKey());
+ }
+
+ System.out.println(info.toString());
+ }
+
+ /**
+ * Print spring app settings.
*
+ * @param springApp spring app instance
*/
- private static OkHttpClient ensureValidHttpClient() {
- if (httpClient == null) {
- httpClient = new OkHttpClient.Builder().readTimeout(1, TimeUnit.MINUTES).build();
+ public static void print(SpringApp springApp) {
+ StringBuilder info = new StringBuilder("Spring Service: ")
+ .append("\n\tId: ").append(springApp.id())
+ .append("\n\tName: ").append(springApp.name())
+ .append("\n\tCreated Time: ").append(springApp.createdTime())
+ .append("\n\tPublic Endpoint: ").append(springApp.isPublic())
+ .append("\n\tUrl: ").append(springApp.url())
+ .append("\n\tHttps Only: ").append(springApp.isHttpsOnly())
+ .append("\n\tFully Qualified Domain Name: ").append(springApp.fqdn())
+ .append("\n\tActive Deployment Name: ").append(springApp.activeDeploymentName());
+
+ if (springApp.temporaryDisk() != null) {
+ info.append("\n\tTemporary Disk:")
+ .append("\n\t\tSize In GB: ").append(springApp.temporaryDisk().sizeInGB())
+ .append("\n\t\tMount Path: ").append(springApp.temporaryDisk().mountPath());
}
- return httpClient;
+ if (springApp.persistentDisk() != null) {
+ info.append("\n\tPersistent Disk:")
+ .append("\n\t\tSize In GB: ").append(springApp.persistentDisk().sizeInGB())
+ .append("\n\t\tMount Path: ").append(springApp.persistentDisk().mountPath());
+ }
+
+ if (springApp.identity() != null) {
+ info.append("\n\tIdentity:")
+ .append("\n\t\tType: ").append(springApp.identity().type())
+ .append("\n\t\tPrincipal Id: ").append(springApp.identity().principalId())
+ .append("\n\t\tTenant Id: ").append(springApp.identity().tenantId());
+ }
+
+ System.out.println(info.toString());
}
/**
- * Connect to a specified URL using "curl" like HTTP GET client.
+ * Sends a GET request to target URL.
+ *
+ * Retry logic tuned for AppService.
+ * The method does not handle 301 redirect.
*
- * @param url URL to be tested
- * @return the HTTP GET response content
+ * @param urlString the target URL.
+ * @return Content of the HTTP response.
*/
- public static String curl(String url) {
- Request request = new Request.Builder().url(url).get().build();
+ public static String sendGetRequest(String urlString) {
+ ClientLogger logger = new ClientLogger(Utils.class);
+
try {
- return ensureValidHttpClient().newCall(request).execute().body().string();
- } catch (IOException e) {
+ Mono>> response =
+ HTTP_CLIENT.getString(getHost(urlString), getPathAndQuery(urlString))
+ .retryWhen(Retry
+ .fixedDelay(5, Duration.ofSeconds(30))
+ .filter(t -> {
+ boolean retry = false;
+ if (t instanceof TimeoutException) {
+ retry = true;
+ } else if (t instanceof HttpResponseException
+ && ((HttpResponseException) t).getResponse().getStatusCode() == 503) {
+ retry = true;
+ }
+
+ if (retry) {
+ logger.info("retry GET request to {}", urlString);
+ }
+ return retry;
+ }));
+ Response ret = stringResponse(response).block();
+ return ret == null ? null : ret.getValue();
+ } catch (MalformedURLException e) {
+ logger.logThrowableAsError(e);
+ return null;
+ }
+ }
+
+ /**
+ * Sends a POST request to target URL.
+ *
+ * Retry logic tuned for AppService.
+ *
+ * @param urlString the target URL.
+ * @param body the request body.
+ * @return Content of the HTTP response.
+ * */
+ public static String sendPostRequest(String urlString, String body) {
+ ClientLogger logger = new ClientLogger(Utils.class);
+
+ try {
+ Mono> response =
+ stringResponse(HTTP_CLIENT.postString(getHost(urlString), getPathAndQuery(urlString), body))
+ .retryWhen(Retry
+ .fixedDelay(5, Duration.ofSeconds(30))
+ .filter(t -> {
+ boolean retry = false;
+ if (t instanceof TimeoutException) {
+ retry = true;
+ }
+
+ if (retry) {
+ logger.info("retry POST request to {}", urlString);
+ }
+ return retry;
+ }));
+ Response ret = response.block();
+ return ret == null ? null : ret.getValue();
+ } catch (Exception e) {
+ logger.logThrowableAsError(e);
return null;
}
}
+
+ private static Mono> stringResponse(Mono>> responseMono) {
+ return responseMono.flatMap(response -> FluxUtil.collectBytesInByteBufferStream(response.getValue())
+ .map(bytes -> new String(bytes, StandardCharsets.UTF_8))
+ .map(str -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), str)));
+ }
+
+ private static String getHost(String urlString) throws MalformedURLException {
+ URL url = new URL(urlString);
+ String protocol = url.getProtocol();
+ String host = url.getAuthority();
+ return protocol + "://" + host;
+ }
+
+ private static String getPathAndQuery(String urlString) throws MalformedURLException {
+ URL url = new URL(urlString);
+ String path = url.getPath();
+ String query = url.getQuery();
+ if (query != null && !query.isEmpty()) {
+ path = path + "?" + query;
+ }
+ return path;
+ }
+
+ private static final WebAppTestClient HTTP_CLIENT = RestProxy.create(
+ WebAppTestClient.class,
+ new HttpPipelineBuilder()
+ .policies(
+ new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)),
+ new RetryPolicy("Retry-After", ChronoUnit.SECONDS))
+ .build());
+
+ @Host("{$host}")
+ @ServiceInterface(name = "WebAppTestClient")
+ private interface WebAppTestClient {
+ @Get("{path}")
+ @ExpectedResponses({200, 400, 404})
+ Mono>> getString(@HostParam("$host") String host, @PathParam(value = "path", encoded = true) String path);
+
+ @Post("{path}")
+ @ExpectedResponses({200, 400, 404})
+ Mono>> postString(@HostParam("$host") String host, @PathParam(value = "path", encoded = true) String path, @BodyParam("text/plain") String body);
+ }
+
+ public static int getSize(Iterable iterable) {
+ int res = 0;
+ Iterator iterator = iterable.iterator();
+ while (iterator.hasNext()) {
+ iterator.next();
+ }
+ return res;
+ }
}
diff --git a/src/main/java/com/microsoft/azure/management/sql/samples/ManageSqlFailoverGroups.java b/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlFailoverGroups.java
similarity index 63%
rename from src/main/java/com/microsoft/azure/management/sql/samples/ManageSqlFailoverGroups.java
rename to src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlFailoverGroups.java
index 1f4cb04..6e3be30 100644
--- a/src/main/java/com/microsoft/azure/management/sql/samples/ManageSqlFailoverGroups.java
+++ b/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlFailoverGroups.java
@@ -1,28 +1,23 @@
-/**
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for
- * license information.
- */
-package com.microsoft.azure.management.sql.samples;
-
-import com.microsoft.azure.AzureEnvironment;
-import com.microsoft.azure.AzureResponseBuilder;
-import com.microsoft.azure.credentials.ApplicationTokenCredentials;
-import com.microsoft.azure.management.Azure;
-import com.microsoft.azure.management.resources.fluentcore.arm.Region;
-import com.microsoft.azure.management.resources.fluentcore.utils.SdkContext;
-import com.microsoft.azure.management.samples.Utils;
-import com.microsoft.azure.management.sql.SampleName;
-import com.microsoft.azure.management.sql.SqlDatabase;
-import com.microsoft.azure.management.sql.SqlDatabaseStandardServiceObjective;
-import com.microsoft.azure.management.sql.SqlFailoverGroup;
-import com.microsoft.azure.management.sql.SqlServer;
-import com.microsoft.azure.serializer.AzureJacksonAdapter;
-import com.microsoft.rest.LogLevel;
-import com.microsoft.rest.RestClient;
-
-import java.io.File;
-import java.util.concurrent.TimeUnit;
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+package com.azure.resourcemanager.sql.samples;
+
+import com.azure.core.credential.TokenCredential;
+import com.azure.core.http.policy.HttpLogDetailLevel;
+import com.azure.core.management.AzureEnvironment;
+import com.azure.identity.DefaultAzureCredentialBuilder;
+import com.azure.resourcemanager.AzureResourceManager;
+import com.azure.core.management.Region;
+import com.azure.core.management.profile.AzureProfile;
+import com.azure.resourcemanager.resources.fluentcore.utils.ResourceManagerUtils;
+import com.azure.resourcemanager.samples.Utils;
+import com.azure.resourcemanager.sql.models.SampleName;
+import com.azure.resourcemanager.sql.models.SqlDatabase;
+import com.azure.resourcemanager.sql.models.SqlDatabaseStandardServiceObjective;
+import com.azure.resourcemanager.sql.models.SqlFailoverGroup;
+import com.azure.resourcemanager.sql.models.SqlServer;
+
+import java.time.Duration;
/**
* Azure SQL sample for managing SQL Failover Groups
@@ -36,18 +31,17 @@
public class ManageSqlFailoverGroups {
/**
* Main function which runs the actual sample.
- * @param azure instance of the azure client
+ * @param azureResourceManager instance of the azure client
* @return true if sample runs successfully
*/
- public static boolean runSample(Azure azure) {
- final String sqlPrimaryServerName = Utils.createRandomName("sqlpri");
- final String sqlSecondaryServerName = Utils.createRandomName("sqlsec");
- final String rgName = Utils.createRandomName("rgsql");
- final String failoverGroupName = Utils.createRandomName("fog");
+ public static boolean runSample(AzureResourceManager azureResourceManager) {
+ final String sqlPrimaryServerName = Utils.randomResourceName(azureResourceManager, "sqlpri", 20);
+ final String sqlSecondaryServerName = Utils.randomResourceName(azureResourceManager, "sqlsec", 20);
+ final String rgName = Utils.randomResourceName(azureResourceManager, "rgsql", 20);
+ final String failoverGroupName = Utils.randomResourceName(azureResourceManager, "fog", 20);
final String dbName = "dbSample";
final String administratorLogin = "sqladmin3423";
- // [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Serves as an example, not for deployment. Please change when using this in your code.")]
- final String administratorPassword = "myS3cureP@ssword";
+ final String administratorPassword = Utils.password();
try {
@@ -55,7 +49,7 @@ public static boolean runSample(Azure azure) {
// Create a primary SQL Server with a sample database.
System.out.println("Creating a primary SQL Server with a sample database");
- SqlServer sqlPrimaryServer = azure.sqlServers().define(sqlPrimaryServerName)
+ SqlServer sqlPrimaryServer = azureResourceManager.sqlServers().define(sqlPrimaryServerName)
.withRegion(Region.US_EAST)
.withNewResourceGroup(rgName)
.withAdministratorLogin(administratorLogin)
@@ -72,7 +66,7 @@ public static boolean runSample(Azure azure) {
// Create a secondary SQL Server with a sample database.
System.out.println("Creating a secondary SQL Server with a sample database");
- SqlServer sqlSecondaryServer = azure.sqlServers().define(sqlSecondaryServerName)
+ SqlServer sqlSecondaryServer = azureResourceManager.sqlServers().define(sqlSecondaryServerName)
.withRegion(Region.US_EAST2)
.withExistingResourceGroup(rgName)
.withAdministratorLogin(administratorLogin)
@@ -98,7 +92,7 @@ public static boolean runSample(Azure azure) {
// Get the Failover Group from the secondary SQL server.
System.out.println("Getting the Failover Group from the secondary SQL server");
- SqlFailoverGroup failoverGroupOnPartner = sqlSecondaryServer.failoverGroups().get(failoverGroup.name());
+ sqlSecondaryServer.failoverGroups().get(failoverGroup.name());
Utils.print(failoverGroup);
@@ -144,7 +138,7 @@ public static boolean runSample(Azure azure) {
// ============================================================
// Get the database from the secondary SQL server.
System.out.println("Getting the database from the secondary server");
- SdkContext.sleep(3 * 60 * 1000);
+ ResourceManagerUtils.sleep(Duration.ofMinutes(3));
db = sqlSecondaryServer.databases().get(dbName);
@@ -160,23 +154,18 @@ public static boolean runSample(Azure azure) {
// Delete the SQL Servers.
System.out.println("Deleting the Sql Servers");
- azure.sqlServers().deleteById(sqlPrimaryServer.id());
- azure.sqlServers().deleteById(sqlSecondaryServer.id());
+ azureResourceManager.sqlServers().deleteById(sqlPrimaryServer.id());
+ azureResourceManager.sqlServers().deleteById(sqlSecondaryServer.id());
return true;
- } catch (Exception f) {
- System.out.println(f.getMessage());
- f.printStackTrace();
} finally {
try {
System.out.println("Deleting Resource Group: " + rgName);
- azure.resourceGroups().deleteByName(rgName);
+ azureResourceManager.resourceGroups().beginDeleteByName(rgName);
System.out.println("Deleted Resource Group: " + rgName);
- }
- catch (Exception e) {
+ } catch (Exception e) {
System.out.println("Did not create any resources in Azure. No clean up is necessary");
}
}
- return false;
}
/**
@@ -185,23 +174,21 @@ public static boolean runSample(Azure azure) {
*/
public static void main(String[] args) {
try {
- final File credFile = new File(System.getenv("AZURE_AUTH_LOCATION"));
-
+ final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE);
+ final TokenCredential credential = new DefaultAzureCredentialBuilder()
+ .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint())
+ .build();
- ApplicationTokenCredentials credentials = ApplicationTokenCredentials.fromFile(credFile);
- RestClient restClient = new RestClient.Builder()
- .withBaseUrl(AzureEnvironment.AZURE, AzureEnvironment.Endpoint.RESOURCE_MANAGER)
- .withSerializerAdapter(new AzureJacksonAdapter())
- .withResponseBuilderFactory(new AzureResponseBuilder.Factory())
- .withReadTimeout(150, TimeUnit.SECONDS)
- .withLogLevel(LogLevel.BODY)
- .withCredentials(credentials).build();
- Azure azure = Azure.authenticate(restClient, credentials.domain(), credentials.defaultSubscriptionId()).withDefaultSubscription();
+ AzureResourceManager azureResourceManager = AzureResourceManager
+ .configure()
+ .withLogLevel(HttpLogDetailLevel.BASIC)
+ .authenticate(credential, profile)
+ .withDefaultSubscription();
// Print selected subscription
- System.out.println("Selected subscription: " + azure.subscriptionId());
+ System.out.println("Selected subscription: " + azureResourceManager.subscriptionId());
- runSample(azure);
+ runSample(azureResourceManager);
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();