From 64684e71b4eb185ab50e5b9c38c35e3878496028 Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Wed, 12 Jan 2022 20:18:18 -0500 Subject: [PATCH 01/43] Add registry resource --- build.gradle | 11 +- examples/registries/registry.gyro | 27 + .../java/gyro/azure/AzureCredentials.java | 48 ++ src/main/java/gyro/azure/AzureResource.java | 9 + .../azure/AzureResourceManagerFinder.java | 71 +++ .../gyro/azure/registries/RegistryFinder.java | 74 +++ .../azure/registries/RegistryResource.java | 471 ++++++++++++++++++ .../java/gyro/azure/registries/Webhook.java | 164 ++++++ .../gyro/azure/registries/package-info.java | 20 + 9 files changed, 892 insertions(+), 3 deletions(-) create mode 100644 examples/registries/registry.gyro create mode 100644 src/main/java/gyro/azure/AzureResourceManagerFinder.java create mode 100644 src/main/java/gyro/azure/registries/RegistryFinder.java create mode 100644 src/main/java/gyro/azure/registries/RegistryResource.java create mode 100644 src/main/java/gyro/azure/registries/Webhook.java create mode 100644 src/main/java/gyro/azure/registries/package-info.java diff --git a/build.gradle b/build.gradle index 15941527..51c2baf5 100644 --- a/build.gradle +++ b/build.gradle @@ -59,10 +59,10 @@ configurations { gyroDoclet } -def azureSdkVersion = '1.31.0' +def azureSdkVersion = '1.41.2' dependencies { - api 'gyro:gyro-core:0.99.6' + (releaseBuild ? '' : '-SNAPSHOT') + api 'gyro:gyro-core:0.99.5' + (releaseBuild ? '' : '-SNAPSHOT') implementation 'com.psddev:dari-util:3.3.607-xe0f27a' implementation 'com.google.guava:guava:23.0' @@ -76,7 +76,12 @@ dependencies { implementation 'com.github.seancfoley:ipaddress:5.0.2' implementation 'org.reflections:reflections:0.9.10' - gyroDoclet 'gyro:gyro-doclet:0.99.1' + implementation 'com.azure.resourcemanager:azure-resourcemanager:2.10.0' + implementation 'com.azure:azure-identity:1.4.2' + implementation 'com.azure:azure-core-http-okhttp:1.7.4' + runtimeOnly 'com.nimbusds:oauth2-oidc-sdk:9.21' + + gyroDoclet 'gyro:gyro-doclet:1.0.0' } task referenceDocs(type: Javadoc) { diff --git a/examples/registries/registry.gyro b/examples/registries/registry.gyro new file mode 100644 index 00000000..18c7e25a --- /dev/null +++ b/examples/registries/registry.gyro @@ -0,0 +1,27 @@ +azure::resource-group resource-group-registry-example + name: "resource-group-registry-example" + + tags: { + Name: "resource-group-registry-example" + } +end + +azure::registry registry-example + name: "registryExample" + sku: "Premium" + resource-group: $(azure::resource-group resource-group-registry-example) + public-network-access: false + admin-user-enabled: false + + tags: { + Name: "registry-example" + } + + webhook + name: "testWebhook" + actions: ["push"] + enabled: true + service-uri: "https://www.google.com" + repository-scope: "foo:*" + end +end diff --git a/src/main/java/gyro/azure/AzureCredentials.java b/src/main/java/gyro/azure/AzureCredentials.java index b9a76271..46dd4dfe 100644 --- a/src/main/java/gyro/azure/AzureCredentials.java +++ b/src/main/java/gyro/azure/AzureCredentials.java @@ -18,9 +18,17 @@ import java.io.IOException; import java.io.InputStream; +import java.net.InetSocketAddress; import java.util.Collections; import java.util.Properties; +import com.azure.core.http.HttpClient; +import com.azure.core.http.ProxyOptions; +import com.azure.core.http.okhttp.OkHttpAsyncHttpClientBuilder; +import com.azure.core.management.profile.AzureProfile; +import com.azure.identity.ClientSecretCredential; +import com.azure.identity.ClientSecretCredentialBuilder; +import com.azure.resourcemanager.AzureResourceManager; import com.microsoft.azure.AzureEnvironment; import com.microsoft.azure.AzureResponseBuilder; import com.microsoft.azure.credentials.ApplicationTokenCredentials; @@ -113,4 +121,44 @@ public Azure createClient() { } } + public AzureResourceManager createResourceManagerClient() { + Properties properties; + + try (InputStream input = openInput(getCredentialFilePath())) { + properties = new Properties(); + + properties.load(input); + + } catch (IOException error) { + throw new GyroException(error.getMessage()); + } + + String tenant = ObjectUtils.to(String.class, properties.get("tenant")); + + ClientSecretCredential credential = new ClientSecretCredentialBuilder() + .clientId(ObjectUtils.to(String.class, properties.get("client"))) + .clientSecret(ObjectUtils.to(String.class, properties.get("key"))) + .tenantId(tenant) + .build(); + + String subscription = ObjectUtils.to(String.class, properties.get("subscription")); + + AzureProfile azureProfile = new AzureProfile(tenant, subscription, com.azure.core.management.AzureEnvironment.AZURE); + + try { + AzureResourceManager.Authenticated authenticated = AzureResourceManager + .configure() + .withHttpClient(new OkHttpAsyncHttpClientBuilder().build()) + .authenticate(credential, azureProfile); + + + return StringUtils.isBlank(subscription) + ? authenticated.withDefaultSubscription() + : authenticated.withSubscription(subscription); + + } catch (Exception error) { + throw new GyroException(error.getMessage(), error); + } + } + } diff --git a/src/main/java/gyro/azure/AzureResource.java b/src/main/java/gyro/azure/AzureResource.java index 6fb0d5d0..ecda41da 100644 --- a/src/main/java/gyro/azure/AzureResource.java +++ b/src/main/java/gyro/azure/AzureResource.java @@ -16,6 +16,7 @@ package gyro.azure; +import com.azure.resourcemanager.AzureResourceManager; import gyro.core.resource.Resource; import com.microsoft.azure.management.Azure; @@ -33,4 +34,12 @@ protected String getRegion() { return credentials(AzureCredentials.class).getRegion(); } + public static AzureResourceManager createResourceManagerClient(AzureCredentials credentials) { + return credentials.createResourceManagerClient(); + } + + protected AzureResourceManager createResourceManagerClient() { + return AzureResource.createResourceManagerClient(credentials(AzureCredentials.class)); + } + } diff --git a/src/main/java/gyro/azure/AzureResourceManagerFinder.java b/src/main/java/gyro/azure/AzureResourceManagerFinder.java new file mode 100644 index 00000000..af07e2cf --- /dev/null +++ b/src/main/java/gyro/azure/AzureResourceManagerFinder.java @@ -0,0 +1,71 @@ +/* + * Copyright 2022, Brightspot, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package gyro.azure; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import com.azure.resourcemanager.AzureResourceManager; +import gyro.core.finder.Finder; + +public abstract class AzureResourceManagerFinder extends Finder { + protected abstract List findAllAzure(AzureResourceManager client); + + protected abstract List findAzure(AzureResourceManager client, Map filters); + + @Override + public List find(Map filters) { + return findAzure(newClient(), convertFilters(filters)).stream() + .map(this::newResource) + .collect(Collectors.toList()); + } + + @Override + public List findAll() { + return findAllAzure(newClient()).stream() + .map(this::newResource) + .collect(Collectors.toList()); + } + + private AzureResourceManager newClient() { + return AzureResource.createResourceManagerClient(credentials(AzureCredentials.class)); + } + + @SuppressWarnings("unchecked") + private R newResource(M model) { + R resource = newResource(); + + if (resource instanceof Copyable) { + ((Copyable) resource).copyFrom(model); + } + + return resource; + } + + @SuppressWarnings("unchecked") + private Map convertFilters(Map query) { + Map filters = new HashMap<>(); + + for (Map.Entry e : query.entrySet()) { + filters.put(e.getKey(), e.getValue().toString()); + } + + return filters; + } +} diff --git a/src/main/java/gyro/azure/registries/RegistryFinder.java b/src/main/java/gyro/azure/registries/RegistryFinder.java new file mode 100644 index 00000000..09543d01 --- /dev/null +++ b/src/main/java/gyro/azure/registries/RegistryFinder.java @@ -0,0 +1,74 @@ +/* + * Copyright 2022, Brightspot, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package gyro.azure.registries; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.containerregistry.models.Registry; +import gyro.azure.AzureResourceManagerFinder; +import gyro.core.Type; + +/** + * Query registry. + * + * Example + * ------- + * + * .. code-block:: gyro + * + * registry: $(external-query azure::registry {}) + */ +@Type("registry") +public class RegistryFinder extends AzureResourceManagerFinder { + + private String id; + + /** + * The id of the registry. + */ + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + @Override + protected List findAllAzure(AzureResourceManager client) { + return client.containerRegistries().list().stream().collect(Collectors.toList()); + } + + @Override + protected List findAzure( + AzureResourceManager client, Map filters) { + + List registries = new ArrayList<>(); + + Registry registry = client.containerRegistries().getById(filters.get("id")); + + if (registry != null) { + registries.add(registry); + } + + return registries; + } +} diff --git a/src/main/java/gyro/azure/registries/RegistryResource.java b/src/main/java/gyro/azure/registries/RegistryResource.java new file mode 100644 index 00000000..13b055dc --- /dev/null +++ b/src/main/java/gyro/azure/registries/RegistryResource.java @@ -0,0 +1,471 @@ +/* + * Copyright 2022, Brightspot, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package gyro.azure.registries; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import com.azure.core.management.Region; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.containerregistry.models.PublicNetworkAccess; +import com.azure.resourcemanager.containerregistry.models.Registry; +import com.azure.resourcemanager.containerregistry.models.Registry.Update; +import com.azure.resourcemanager.containerregistry.models.Webhook.UpdateResourceStages.WithAttach; +import com.azure.resourcemanager.containerregistry.models.WebhookAction; +import gyro.azure.AzureResource; +import gyro.azure.Copyable; +import gyro.azure.resources.ResourceGroupResource; +import gyro.core.GyroException; +import gyro.core.GyroUI; +import gyro.core.Type; +import gyro.core.resource.Id; +import gyro.core.resource.Output; +import gyro.core.resource.Resource; +import gyro.core.resource.Updatable; +import gyro.core.scope.State; +import gyro.core.validation.Required; +import gyro.core.validation.ValidStrings; +import gyro.core.validation.ValidationError; + +/** + * Creates a registry. + * + * Example + * ------- + * + * .. code-block:: gyro + * + * azure::registry registry-example + * name: "registry-example" + * sku: "Standard" + * resource-group: $(azure::resource-group resource-group-registry-example) + * public-network-access: false + * admin-user-enabled: false + * + * tags: { + * Name: "registry-example" + * } + * end + */ +@Type("registry") +public class RegistryResource extends AzureResource implements Copyable { + + private String name; + private ResourceGroupResource resourceGroup; + private String sku; + private Boolean adminUserEnabled; + private Boolean publicNetworkAccess; + private Map tags; + private Set webhook; + + private String id; + private String creationDate; + private String loginServerUrl; + + /** + * The name of the registry. + */ + @Id + @Required + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + /** + * The resource group under which the registry will reside. + */ + @Required + public ResourceGroupResource getResourceGroup() { + return resourceGroup; + } + + public void setResourceGroup(ResourceGroupResource resourceGroup) { + this.resourceGroup = resourceGroup; + } + + /** + * The type of sku. + */ + @Required + @Updatable + @ValidStrings({"Standard", "Premium", "Basic"}) + public String getSku() { + return sku; + } + + public void setSku(String sku) { + this.sku = sku; + } + + /** + * If set to ``true`` enables admin user for the registry. Defaults to ``false``. + */ + @Updatable + public Boolean getAdminUserEnabled() { + if (adminUserEnabled == null) { + adminUserEnabled = false; + } + + return adminUserEnabled; + } + + public void setAdminUserEnabled(Boolean adminUserEnabled) { + this.adminUserEnabled = adminUserEnabled; + } + + /** + * If set to ``true`` enables public network access to this registry. Defaults to ``true``. + */ + @Updatable + public Boolean getPublicNetworkAccess() { + if (publicNetworkAccess == null) { + publicNetworkAccess = true; + } + + return publicNetworkAccess; + } + + public void setPublicNetworkAccess(Boolean publicNetworkAccess) { + this.publicNetworkAccess = publicNetworkAccess; + } + + /** + * The tags for the registry. + */ + @Updatable + public Map getTags() { + if (tags == null) { + tags = new HashMap<>(); + } + + return tags; + } + + public void setTags(Map tags) { + this.tags = tags; + } + + /** + * A set of webhooks for the registry. + */ + @Updatable + public Set getWebhook() { + if (webhook == null) { + webhook = new HashSet<>(); + } + + return webhook; + } + + public void setWebhook(Set webhook) { + this.webhook = webhook; + } + + /** + * The id of the registry. + */ + @Output + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + /** + * The creation date of the registry. + */ + @Output + public String getCreationDate() { + return creationDate; + } + + public void setCreationDate(String creationDate) { + this.creationDate = creationDate; + } + + /** + * The login server url of the registry. + */ + @Output + public String getLoginServerUrl() { + return loginServerUrl; + } + + public void setLoginServerUrl(String loginServerUrl) { + this.loginServerUrl = loginServerUrl; + } + + @Override + public void copyFrom(Registry registry) { + setName(registry.name()); + setAdminUserEnabled(registry.adminUserEnabled()); + setCreationDate(registry.creationDate().toString()); + setId(registry.id()); + setSku(registry.sku().name().toString()); + setTags(registry.tags()); + setResourceGroup(findById(ResourceGroupResource.class, registry.resourceGroupName())); + setPublicNetworkAccess(registry.publicNetworkAccess().equals(PublicNetworkAccess.ENABLED)); + setLoginServerUrl(registry.loginServerUrl()); + + getWebhook().clear(); + if (registry.webhooks() != null) { + registry.webhooks().list().forEach(hook -> { + Webhook webhook = newSubresource(Webhook.class); + webhook.copyFrom(hook); + getWebhook().add(webhook); + }); + } + } + + @Override + public boolean refresh() { + AzureResourceManager client = createResourceManagerClient(); + + Registry registry = client.containerRegistries() + .getByResourceGroup(getResourceGroup().getName(), getName()); + + if (registry == null) { + return false; + } + + copyFrom(registry); + + return true; + } + + @Override + public void create(GyroUI ui, State state) throws Exception { + AzureResourceManager client = createResourceManagerClient(); + + Registry.DefinitionStages.WithSku withSku = client.containerRegistries() + .define(getName()) + .withRegion(Region.fromName(getRegion())) + .withExistingResourceGroup(getResourceGroup().getName()); + + Registry.DefinitionStages.WithCreate withCreate; + + if (getSku().equals("Standard")) { + withCreate = withSku.withStandardSku(); + } else if (getSku().equals("Basic")) { + withCreate = withSku.withBasicSku(); + } else if (getSku().equals("Premium")) { + withCreate = withSku.withPremiumSku(); + } else { + // Unreachable valid string on sku should take care of it. + throw new GyroException("Invalid sku option"); + } + + if (!getTags().isEmpty()) { + withCreate = withCreate.withTags(getTags()); + } + + if (getAdminUserEnabled()) { + withCreate = withCreate.withRegistryNameAsAdminUser(); + } + + if (!getPublicNetworkAccess()) { + withCreate = withCreate.disablePublicNetworkAccess(); + } + + Registry registry = withCreate.create(); + + setId(registry.id()); + setCreationDate(registry.creationDate().toString()); + + if (!getWebhook().isEmpty()) { + HashSet currentWebhooks = new HashSet<>(getWebhook()); + getWebhook().clear(); + state.save(); + + setWebhook(currentWebhooks); + Update update = registry.update(); + + update = updateWebhooks(update, null); + update.apply(); + } + + copyFrom(registry); + } + + @Override + public void update( + GyroUI ui, State state, Resource current, Set changedFieldNames) throws Exception { + AzureResourceManager client = createResourceManagerClient(); + + Registry registry = client.containerRegistries() + .getByResourceGroup(getResourceGroup().getName(), getName()); + + Update update = registry.update(); + + if (changedFieldNames.contains("tags")) { + update = update.withTags(getTags()); + } + + if (changedFieldNames.contains("public-network-access")) { + if (getPublicNetworkAccess()) { + update = update.enablePublicNetworkAccess(); + } else { + update = update.disablePublicNetworkAccess(); + } + } + + if (changedFieldNames.contains("sku")) { + if (getSku().equals("Standard")) { + update = update.withStandardSku(); + } else if (getSku().equals("Basic")) { + update = update.withBasicSku(); + } else if (getSku().equals("Premium")) { + update = update.withPremiumSku(); + } else { + // Unreachable valid string on sku should take care of it. + throw new GyroException("Invalid sku option"); + } + } + + if (changedFieldNames.contains("admin-user-enabled")) { + if (getAdminUserEnabled()) { + update = update.withRegistryNameAsAdminUser(); + } else { + update = update.withoutRegistryNameAsAdminUser(); + } + } + + if (changedFieldNames.contains("webhook")) { + RegistryResource oldResource = (RegistryResource) current; + + update = updateWebhooks(update, oldResource.getWebhook()); + } + + update.apply(); + } + + @Override + public void delete(GyroUI ui, State state) throws Exception { + AzureResourceManager client = createResourceManagerClient(); + + client.containerRegistries().deleteByResourceGroup(getResourceGroup().getName(), getName()); + } + + private Update updateWebhooks(Update update, Set oldWebhooks) { + if (oldWebhooks == null) { + oldWebhooks = new HashSet<>(); + } + + Set oldWebhookNames = oldWebhooks.stream().map(Webhook::getName).collect(Collectors.toSet()); + Set newWebhookNames = getWebhook().stream().map(Webhook::getName).collect(Collectors.toSet()); + + Set addWebhooks = getWebhook().stream() + .filter(o -> !oldWebhookNames.contains(o.getName())) + .collect(Collectors.toSet()); + + Set removeWebhooks = oldWebhooks.stream() + .filter(o -> !newWebhookNames.contains(o.getName())) + .collect(Collectors.toSet()); + + Set updateWebhooks = getWebhook().stream() + .filter(o -> oldWebhookNames.contains(o.getName())) + .collect(Collectors.toSet()); + + if (!removeWebhooks.isEmpty()) { + for (Webhook webhook : removeWebhooks) { + update = update.withoutWebhook(webhook.getName()); + } + } + + if (!updateWebhooks.isEmpty()) { + for (Webhook webhook : updateWebhooks) { + WithAttach updateWithAttach = update + .updateWebhook(webhook.getName()) + .withTriggerWhen(webhook.getActions() + .stream() + .map(WebhookAction::fromString) + .toArray(WebhookAction[]::new)) + .withServiceUri(webhook.getServiceUri()) + .enabled(webhook.getEnabled()) + .withRepositoriesScope(webhook.getRepositoryScope()) + .withTags(null) + .withCustomHeaders(null); + + if (!webhook.getTags().isEmpty()) { + for (String key : webhook.getTags().keySet()) { + updateWithAttach = updateWithAttach.withTag(key, webhook.getTags().get(key)); + } + } + + if (!webhook.getCustomHeaders().isEmpty()) { + for (String key : webhook.getCustomHeaders().keySet()) { + updateWithAttach = updateWithAttach.withCustomHeader(key, webhook.getCustomHeaders().get(key)); + } + } + + update = updateWithAttach.parent(); + } + } + + if (!addWebhooks.isEmpty()) { + for (Webhook webhook : addWebhooks) { + com.azure.resourcemanager.containerregistry.models.Webhook.UpdateDefinitionStages.WithAttach updateWithAttach = update + .defineWebhook(webhook.getName()) + .withTriggerWhen(webhook.getActions() + .stream() + .map(WebhookAction::fromString) + .toArray(WebhookAction[]::new)) + .withServiceUri(webhook.getServiceUri()) + .enabled(webhook.getEnabled()) + .withRepositoriesScope(webhook.getRepositoryScope()); + + if (!webhook.getTags().isEmpty()) { + for (String key : webhook.getTags().keySet()) { + updateWithAttach = updateWithAttach.withTag(key, webhook.getTags().get(key)); + } + } + + if (!webhook.getCustomHeaders().isEmpty()) { + for (String key : webhook.getCustomHeaders().keySet()) { + updateWithAttach = updateWithAttach.withCustomHeader(key, webhook.getCustomHeaders().get(key)); + } + } + + update = updateWithAttach.attach(); + } + } + + return update; + } + + @Override + public List validate(Set configuredFields) { + List validationErrors = new ArrayList<>(); + + if (!getPublicNetworkAccess() && !"Premium".equals(getSku())) { + validationErrors.add(new ValidationError(this, "public-network-access", "cannot be set to `false` when 'sku' is not set to `Premium`.")); + } + + return validationErrors; + } +} diff --git a/src/main/java/gyro/azure/registries/Webhook.java b/src/main/java/gyro/azure/registries/Webhook.java new file mode 100644 index 00000000..e9800483 --- /dev/null +++ b/src/main/java/gyro/azure/registries/Webhook.java @@ -0,0 +1,164 @@ +/* + * Copyright 2022, Brightspot, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package gyro.azure.registries; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import com.azure.core.util.ExpandableStringEnum; +import gyro.azure.Copyable; +import gyro.core.resource.Diffable; +import gyro.core.resource.Updatable; +import gyro.core.validation.CollectionMin; +import gyro.core.validation.Regex; +import gyro.core.validation.Required; +import gyro.core.validation.ValidStrings; + +public class Webhook extends Diffable implements Copyable { + + private String name; + private Set actions; + private Map customHeaders; + private Boolean enabled; + private String serviceUri; + private String repositoryScope; + private Map tags; + + /** + * The name of the webhook. + */ + @Required + @Regex(value = "[a-zA-Z0-9]{5,50}", message = "5-50 characters long an supporting only alpha numeric values") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + /** + * Actions for the webhook. + */ + @Required + @CollectionMin(1) + @Updatable + @ValidStrings({"push", "delete", "quarantine", "chart_push", "chart_delete"}) + public Set getActions() { + if (actions == null) { + actions = new HashSet<>(); + } + + return actions; + } + + public void setActions(Set actions) { + this.actions = actions; + } + + /** + * A list of custom headers for the webhook. + */ + @Updatable + public Map getCustomHeaders() { + if (customHeaders == null) { + customHeaders = new HashMap<>(); + } + + return customHeaders; + } + + public void setCustomHeaders(Map customHeaders) { + this.customHeaders = customHeaders; + } + + /** + * Enabled if set to ``true``. + */ + @Updatable + public Boolean getEnabled() { + if (enabled == null) { + enabled = false; + } + + return enabled; + } + + public void setEnabled(Boolean enabled) { + this.enabled = enabled; + } + + /** + * The service url for the webhook. + */ + @Required + @Updatable + public String getServiceUri() { + return serviceUri; + } + + public void setServiceUri(String serviceUri) { + this.serviceUri = serviceUri; + } + + /** + * The scope for the webhook. + */ + @Updatable + public String getRepositoryScope() { + return repositoryScope; + } + + public void setRepositoryScope(String repositoryScope) { + this.repositoryScope = repositoryScope; + } + + /** + * A set of tags for the webhook. + */ + @Updatable + public Map getTags() { + if (tags == null) { + tags = new HashMap<>(); + } + + return tags; + } + + public void setTags(Map tags) { + this.tags = tags; + } + + @Override + public void copyFrom(com.azure.resourcemanager.containerregistry.models.Webhook model) { + setName(model.name()); + setActions(model.triggers().stream().map(ExpandableStringEnum::toString).collect(Collectors.toSet())); + setCustomHeaders(model.customHeaders()); + setEnabled(model.isEnabled()); + setServiceUri(model.serviceUri()); + setRepositoryScope(model.scope()); + setTags(model.tags()); + } + + @Override + public String primaryKey() { + return getName(); + } +} diff --git a/src/main/java/gyro/azure/registries/package-info.java b/src/main/java/gyro/azure/registries/package-info.java new file mode 100644 index 00000000..c6937cac --- /dev/null +++ b/src/main/java/gyro/azure/registries/package-info.java @@ -0,0 +1,20 @@ +/* + * Copyright 2022, Brightspot, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@DocGroup("Registries") +package gyro.azure.registries; + +import gyro.core.resource.DocGroup; From 4399d252af854bd461ff245f759fa21f3dc27b4c Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Mon, 31 Jan 2022 23:06:36 -0500 Subject: [PATCH 02/43] bump bom version --- build.gradle | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/build.gradle b/build.gradle index 51c2baf5..578d063c 100644 --- a/build.gradle +++ b/build.gradle @@ -76,10 +76,10 @@ dependencies { implementation 'com.github.seancfoley:ipaddress:5.0.2' implementation 'org.reflections:reflections:0.9.10' - implementation 'com.azure.resourcemanager:azure-resourcemanager:2.10.0' - implementation 'com.azure:azure-identity:1.4.2' - implementation 'com.azure:azure-core-http-okhttp:1.7.4' - runtimeOnly 'com.nimbusds:oauth2-oidc-sdk:9.21' + implementation 'com.azure.resourcemanager:azure-resourcemanager:2.11.0' + implementation 'com.azure:azure-identity:1.4.3' + implementation 'com.azure:azure-core-http-okhttp:1.7.8' + runtimeOnly 'com.nimbusds:oauth2-oidc-sdk:9.22.1' gyroDoclet 'gyro:gyro-doclet:1.0.0' } From 822ee28f5835ad8085c7d66302a1b60f0ee4ab4a Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Mon, 31 Jan 2022 23:15:40 -0500 Subject: [PATCH 03/43] Update client resource group --- .../gyro/azure/resources/ResourceGroupFinder.java | 15 ++++++++------- .../azure/resources/ResourceGroupResource.java | 14 +++++++------- 2 files changed, 15 insertions(+), 14 deletions(-) diff --git a/src/main/java/gyro/azure/resources/ResourceGroupFinder.java b/src/main/java/gyro/azure/resources/ResourceGroupFinder.java index 09a310c7..e442986c 100644 --- a/src/main/java/gyro/azure/resources/ResourceGroupFinder.java +++ b/src/main/java/gyro/azure/resources/ResourceGroupFinder.java @@ -16,14 +16,15 @@ package gyro.azure.resources; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.resources.ResourceGroup; -import gyro.azure.AzureFinder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.resources.models.ResourceGroup; +import gyro.azure.AzureResourceManagerFinder; import gyro.core.Type; import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; /** * Query resource group. @@ -36,7 +37,7 @@ * resource-group: $(external-query azure::resource-group {}) */ @Type("resource-group") -public class ResourceGroupFinder extends AzureFinder { +public class ResourceGroupFinder extends AzureResourceManagerFinder { private String name; /** @@ -51,12 +52,12 @@ public void setName(String name) { } @Override - protected List findAllAzure(Azure client) { - return client.resourceGroups().list(); + protected List findAllAzure(AzureResourceManager client) { + return client.resourceGroups().list().stream().collect(Collectors.toList()); } @Override - protected List findAzure(Azure client, Map filters) { + protected List findAzure(AzureResourceManager client, Map filters) { if (client.resourceGroups().contain(filters.get("name"))) { return Collections.singletonList(client.resourceGroups().getByName(filters.get("name"))); } else { diff --git a/src/main/java/gyro/azure/resources/ResourceGroupResource.java b/src/main/java/gyro/azure/resources/ResourceGroupResource.java index 3db8cc0e..a8aaeff8 100644 --- a/src/main/java/gyro/azure/resources/ResourceGroupResource.java +++ b/src/main/java/gyro/azure/resources/ResourceGroupResource.java @@ -16,6 +16,9 @@ package gyro.azure.resources; +import com.azure.core.management.Region; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.resources.models.ResourceGroup; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.core.GyroUI; @@ -24,9 +27,6 @@ import gyro.core.Type; import gyro.core.resource.Output; import gyro.core.resource.Resource; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.resources.ResourceGroup; -import com.microsoft.azure.management.resources.fluentcore.arm.Region; import gyro.core.scope.State; import gyro.core.validation.Required; @@ -107,7 +107,7 @@ public void copyFrom(ResourceGroup resourceGroup) { @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); if (!client.resourceGroups().contain(getName())) { return false; @@ -121,7 +121,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); ResourceGroup resourceGroup = client.resourceGroups() .define(getName()) @@ -134,7 +134,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); ResourceGroup resourceGroup = client.resourceGroups().getByName(getName()); @@ -143,7 +143,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); client.resourceGroups().deleteByName(getName()); } From c523ae13255162b7e7178e0b9b43f6117984c0c2 Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Mon, 31 Jan 2022 23:15:58 -0500 Subject: [PATCH 04/43] Update client network --- .../gyro/azure/network/NetworkFinder.java | 15 ++++++++------- .../gyro/azure/network/NetworkResource.java | 19 ++++++++++--------- 2 files changed, 18 insertions(+), 16 deletions(-) diff --git a/src/main/java/gyro/azure/network/NetworkFinder.java b/src/main/java/gyro/azure/network/NetworkFinder.java index 916fb1ca..24ab205a 100644 --- a/src/main/java/gyro/azure/network/NetworkFinder.java +++ b/src/main/java/gyro/azure/network/NetworkFinder.java @@ -16,17 +16,18 @@ package gyro.azure.network; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.network.Network; -import gyro.azure.AzureFinder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.network.models.Network; +import gyro.azure.AzureResourceManagerFinder; import gyro.core.Type; import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; @Type("network") -public class NetworkFinder extends AzureFinder { +public class NetworkFinder extends AzureResourceManagerFinder { private String id; /** @@ -41,12 +42,12 @@ public void setId(String id) { } @Override - protected List findAllAzure(Azure client) { - return client.networks().list(); + protected List findAllAzure(AzureResourceManager client) { + return client.networks().list().stream().collect(Collectors.toList()); } @Override - protected List findAzure(Azure client, Map filters) { + protected List findAzure(AzureResourceManager client, Map filters) { Network network = client.networks().getById(filters.get("id")); if (network == null) { return Collections.emptyList(); diff --git a/src/main/java/gyro/azure/network/NetworkResource.java b/src/main/java/gyro/azure/network/NetworkResource.java index a137b20d..47dab934 100644 --- a/src/main/java/gyro/azure/network/NetworkResource.java +++ b/src/main/java/gyro/azure/network/NetworkResource.java @@ -16,10 +16,11 @@ package gyro.azure.network; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.network.Network; -import com.microsoft.azure.management.network.Subnet; -import com.microsoft.azure.management.resources.fluentcore.arm.Region; + +import com.azure.core.management.Region; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.network.models.Network; +import com.azure.resourcemanager.network.models.Subnet; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.azure.resources.ResourceGroupResource; @@ -244,7 +245,7 @@ public void copyFrom(Network network) { @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); Network network = client.networks().getById(getId()); @@ -259,7 +260,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); Network.DefinitionStages.WithCreate networkDefWithoutAddress = client.networks() .define(getName()) @@ -283,7 +284,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); Network network = client.networks().getById(getId()); @@ -321,12 +322,12 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); client.networks().deleteById(getId()); } - Network getNetwork(Azure client) { + Network getNetwork(AzureResourceManager client) { return client.networks().getById(getId()); } } From de06dbd536746c3bddbcef239244902da9d6d8f1 Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Mon, 31 Jan 2022 23:16:10 -0500 Subject: [PATCH 05/43] Update client subnetwork --- .../gyro/azure/network/SubnetResource.java | 22 ++++++++++--------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/src/main/java/gyro/azure/network/SubnetResource.java b/src/main/java/gyro/azure/network/SubnetResource.java index 9676d5d8..9caa1721 100644 --- a/src/main/java/gyro/azure/network/SubnetResource.java +++ b/src/main/java/gyro/azure/network/SubnetResource.java @@ -16,20 +16,22 @@ package gyro.azure.network; +import com.azure.core.management.Region; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.network.models.Network; +import com.azure.resourcemanager.network.models.ServiceEndpointType; +import com.azure.resourcemanager.network.models.Subnet; import com.psddev.dari.util.ObjectUtils; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.core.GyroException; import gyro.core.GyroUI; +import gyro.core.resource.Id; import gyro.core.resource.Output; import gyro.core.resource.Updatable; import gyro.core.resource.Resource; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.network.Network; -import com.microsoft.azure.management.network.ServiceEndpointType; -import com.microsoft.azure.management.network.Subnet; -import com.microsoft.azure.management.resources.fluentcore.arm.Region; + import gyro.core.scope.State; import gyro.core.validation.Required; @@ -63,7 +65,7 @@ public class SubnetResource extends AzureResource implements Copyable { private RouteTableResource routeTable; private Map> serviceEndpoints; private String id; - + /** * The address prefix in CIDR notation. */ @@ -157,7 +159,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); NetworkResource parent = (NetworkResource) parent(); @@ -182,12 +184,12 @@ public void create(GyroUI ui, State state) { } Network response = updateWithAttach.attach().apply(); - setId(response.subnets().get(getName()).inner().id()); + setId(response.subnets().get(getName()).id()); } @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); NetworkResource parent = (NetworkResource) parent(); @@ -233,7 +235,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); NetworkResource parent = (NetworkResource) parent(); From 61cbc069021827b3cd5feaaaf72ed4571315a87b Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Mon, 31 Jan 2022 23:16:57 -0500 Subject: [PATCH 06/43] Update client public ip address --- .../azure/network/PublicIpAddressFinder.java | 17 +++---- .../network/PublicIpAddressResource.java | 46 +++++++++---------- 2 files changed, 32 insertions(+), 31 deletions(-) diff --git a/src/main/java/gyro/azure/network/PublicIpAddressFinder.java b/src/main/java/gyro/azure/network/PublicIpAddressFinder.java index 40298e15..596adbf6 100644 --- a/src/main/java/gyro/azure/network/PublicIpAddressFinder.java +++ b/src/main/java/gyro/azure/network/PublicIpAddressFinder.java @@ -16,14 +16,15 @@ package gyro.azure.network; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.network.PublicIPAddress; -import gyro.azure.AzureFinder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.network.models.PublicIpAddress; +import gyro.azure.AzureResourceManagerFinder; import gyro.core.Type; import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; /** * Query public ip address. @@ -36,7 +37,7 @@ * public-ip-address: $(external-query azure::public-ip-address {}) */ @Type("public-ip-address") -public class PublicIpAddressFinder extends AzureFinder { +public class PublicIpAddressFinder extends AzureResourceManagerFinder { private String id; /** @@ -51,13 +52,13 @@ public void setId(String id) { } @Override - protected List findAllAzure(Azure client) { - return client.publicIPAddresses().list(); + protected List findAllAzure(AzureResourceManager client) { + return client.publicIpAddresses().list().stream().collect(Collectors.toList()); } @Override - protected List findAzure(Azure client, Map filters) { - PublicIPAddress publicIPAddress = client.publicIPAddresses().getById(filters.get("id")); + protected List findAzure(AzureResourceManager client, Map filters) { + PublicIpAddress publicIPAddress = client.publicIpAddresses().getById(filters.get("id")); if (publicIPAddress == null) { return Collections.emptyList(); } else { diff --git a/src/main/java/gyro/azure/network/PublicIpAddressResource.java b/src/main/java/gyro/azure/network/PublicIpAddressResource.java index e5636144..946469c8 100644 --- a/src/main/java/gyro/azure/network/PublicIpAddressResource.java +++ b/src/main/java/gyro/azure/network/PublicIpAddressResource.java @@ -16,15 +16,15 @@ package gyro.azure.network; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.network.IPAllocationMethod; -import com.microsoft.azure.management.network.IpTag; -import com.microsoft.azure.management.network.PublicIPAddress; -import com.microsoft.azure.management.network.PublicIPAddress.DefinitionStages.WithCreate; -import com.microsoft.azure.management.network.PublicIPSkuType; -import com.microsoft.azure.management.resources.fluentcore.arm.AvailabilityZoneId; -import com.microsoft.azure.management.resources.fluentcore.arm.ExpandableStringEnum; -import com.microsoft.azure.management.resources.fluentcore.arm.Region; + +import com.azure.core.management.Region; +import com.azure.core.util.ExpandableStringEnum; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.network.models.IpAllocationMethod; +import com.azure.resourcemanager.network.models.IpTag; +import com.azure.resourcemanager.network.models.PublicIPSkuType; +import com.azure.resourcemanager.network.models.PublicIpAddress; +import com.azure.resourcemanager.resources.fluentcore.arm.AvailabilityZoneId; import com.psddev.dari.util.ObjectUtils; import gyro.azure.AzureResource; import gyro.azure.Copyable; @@ -65,7 +65,7 @@ * end */ @Type("public-ip-address") -public class PublicIpAddressResource extends AzureResource implements Copyable { +public class PublicIpAddressResource extends AzureResource implements Copyable { private String name; private ResourceGroupResource resourceGroup; private SKU_TYPE skuType; @@ -297,14 +297,14 @@ public void setVersion(String version) { } @Override - public void copyFrom(PublicIPAddress publicIpAddress) { + public void copyFrom(PublicIpAddress publicIpAddress) { setIpAddress(publicIpAddress.ipAddress()); setDomainLabel(publicIpAddress.leafDomainLabel()); setIdleTimeoutInMinute(publicIpAddress.idleTimeoutInMinutes()); setTags(publicIpAddress.tags()); setId(publicIpAddress.id()); setName(publicIpAddress.name()); - setIsDynamic(publicIpAddress.ipAllocationMethod().equals(IPAllocationMethod.DYNAMIC)); + setIsDynamic(publicIpAddress.ipAllocationMethod().equals(IpAllocationMethod.DYNAMIC)); setSkuType(publicIpAddress.sku().equals(PublicIPSkuType.BASIC) ? SKU_TYPE.BASIC : SKU_TYPE.STANDARD); setAvailabilityZoneIds(publicIpAddress.availabilityZones().stream().map(ExpandableStringEnum::toString).collect(Collectors.toSet())); setResourceGroup(findById(ResourceGroupResource.class, publicIpAddress.resourceGroupName())); @@ -318,9 +318,9 @@ public void copyFrom(PublicIPAddress publicIpAddress) { @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); - PublicIPAddress publicIpAddress = client.publicIPAddresses().getById(getId()); + PublicIpAddress publicIpAddress = client.publicIpAddresses().getById(getId()); if (publicIpAddress == null) { return false; @@ -333,9 +333,9 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); - WithCreate withCreate = client.publicIPAddresses() + PublicIpAddress.DefinitionStages.WithCreate withCreate = client.publicIpAddresses() .define(getName()) .withRegion(Region.fromName(getRegion())) .withExistingResourceGroup(getResourceGroup().getName()) @@ -374,18 +374,18 @@ public void create(GyroUI ui, State state) { } } - PublicIPAddress publicIpAddress = withCreate.withTags(getTags()).create(); + PublicIpAddress publicIpAddress = withCreate.withTags(getTags()).create(); copyFrom(publicIpAddress); } @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); - PublicIPAddress publicIpAddress = client.publicIPAddresses().getById(getId()); + PublicIpAddress publicIpAddress = client.publicIpAddresses().getById(getId()); - PublicIPAddress.Update update = publicIpAddress.update(); + PublicIpAddress.Update update = publicIpAddress.update(); if (changedFieldNames.contains("idle-timeout-in-minute")) { update = update.withIdleTimeoutInMinutes(getIdleTimeoutInMinute()); @@ -417,14 +417,14 @@ public void update(GyroUI ui, State state, Resource current, Set changed } if (!changedFieldNames.isEmpty()) { - PublicIPAddress response = update.apply(); + PublicIpAddress response = update.apply(); copyFrom(response); } } @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); - client.publicIPAddresses().deleteById(getId()); + AzureResourceManager client = createResourceManagerClient(); + client.publicIpAddresses().deleteById(getId()); } } From 39fa4320c4f6374fececeabe01a3bf4b6e87b182 Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Tue, 1 Feb 2022 01:57:37 -0500 Subject: [PATCH 07/43] Add resource aks --- .../containerservice/kubernetes-cluster.gyro | 105 +++ .../containerservice/ClusterAddonProfile.java | 82 ++ .../containerservice/ClusterAgentPool.java | 410 ++++++++++ ...ClusterLoadBalancerManagedOutboundIps.java | 39 + ...ClusterLoadBalancerOutboundIpPrefixes.java | 52 ++ .../ClusterLoadBalancerOutboundIps.java | 56 ++ .../ClusterLoadBalancerProfile.java | 185 +++++ .../ClusterManagedOutboundIpProfile.java | 37 + .../ClusterNatGatewayProfile.java | 102 +++ .../ClusterPropertiesAutoScalerProfile.java | 318 ++++++++ .../KubernetesClusterFinder.java | 58 ++ .../KubernetesClusterResource.java | 721 ++++++++++++++++++ .../containerservice/NetworkProfile.java | 252 ++++++ 13 files changed, 2417 insertions(+) create mode 100644 examples/containerservice/kubernetes-cluster.gyro create mode 100644 src/main/java/gyro/azure/containerservice/ClusterAddonProfile.java create mode 100644 src/main/java/gyro/azure/containerservice/ClusterAgentPool.java create mode 100644 src/main/java/gyro/azure/containerservice/ClusterLoadBalancerManagedOutboundIps.java create mode 100644 src/main/java/gyro/azure/containerservice/ClusterLoadBalancerOutboundIpPrefixes.java create mode 100644 src/main/java/gyro/azure/containerservice/ClusterLoadBalancerOutboundIps.java create mode 100644 src/main/java/gyro/azure/containerservice/ClusterLoadBalancerProfile.java create mode 100644 src/main/java/gyro/azure/containerservice/ClusterManagedOutboundIpProfile.java create mode 100644 src/main/java/gyro/azure/containerservice/ClusterNatGatewayProfile.java create mode 100644 src/main/java/gyro/azure/containerservice/ClusterPropertiesAutoScalerProfile.java create mode 100644 src/main/java/gyro/azure/containerservice/KubernetesClusterFinder.java create mode 100644 src/main/java/gyro/azure/containerservice/KubernetesClusterResource.java create mode 100644 src/main/java/gyro/azure/containerservice/NetworkProfile.java diff --git a/examples/containerservice/kubernetes-cluster.gyro b/examples/containerservice/kubernetes-cluster.gyro new file mode 100644 index 00000000..0ff39708 --- /dev/null +++ b/examples/containerservice/kubernetes-cluster.gyro @@ -0,0 +1,105 @@ +azure::resource-group resource-group-cluster-example + name: "resource-group-cluster-example" + + tags: { + Name: "resource-group-cluster-example" + } +end + +azure::network network-cluster-example + name: "network-cluster-example" + resource-group: $(azure::resource-group resource-group-cluster-example) + address-spaces: [ + "10.0.0.0/8" + ] + + subnet + address-prefix: "10.240.0.0/16" + name: "subnet1" + end + + tags: { + Name: "network-cluster-example" + } +end + +azure::registry registry-example-cluster + name: "registryClusterExample" + sku: "Premium" + resource-group: $(azure::resource-group resource-group-cluster-example) + public-network-access: false + admin-user-enabled: false + + tags: { + Name: "registry-example-cluster" + } +end + +azure::public-ip-address public-ip-address-example-cluster + name: "public-ip-address-example-cluster" + resource-group: $(azure::resource-group resource-group-cluster-example) + idle-timeout-in-minute: 4 + sku-type: "STANDARD" + tags: { + Name: "public-ip-address-example-cluster" + } +end + +azure::kubernetes-cluster kubernetes-cluster-example + name: "kubernetes-cluster-example" + version: "1.22.4" + enable-private-cluster: false + + resource-group: $(azure::resource-group resource-group-cluster-example) + + linux-root-username: "adminuser" + ssh-key: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDK/2jCF+4AF3aJ+d1f4yjVECuYaXYGj2z4Nu4nc6zFX1cgSm4ukI+CDlbbYjDGiHblkDbuGg067KsnjFAH6xrUpmOu4XO9NJz8GuCD0TEE+EG39PcpY1A+mfKyFNK7RvWpf2GB5nWXUvDzek1j9FqnRktE1Bj/Zyj2nBG/ymAZF+zHMgZ8PecDjdPeSSkUzkuMoOdNqjFXhRGd1p4upbVWtyq7rQHi1mPfEv7pllF8H48+nTFx5/crT7/AhOBtVpQJPM+bahy+4H2gF3Pek91v608DkbnjvszUmyhghHQOOnseIJ+bgJVumMNXwxATVAe/weqMAF/sGtJrkuBFJkl274TQzfmM+Z09YtuiIbBBCnwF1MeXC3Fbb3f8E7yFBJ3T8Mt9wxc9elDZA+ziFhHmQrMdfEyQiyq+h5Q+GMiXkAYk0Ikuc1MCprYkplb1aR5oOGVha6UFOu7NqRvrFjscVaetZ0UEHv0AZhb54N7/x6DPCwzTaw/3iYhhSu1we3k= generated-by-azure" + + dns-prefix: "kubernetes-cluster-example-dns" + enable-rbac: true + + agent-pool + name: "agentpool" + size: "Standard_DS2_v2" + count: 1 + availability-zones: [1,2,3] + mode: "System" + auto-scaling-enabled: true + type: "VirtualMachineScaleSets" + os-type: "Linux" + os-disk-type: "Managed" + os-disk-size-in-gb: 128 + node-size: 1 + network: $(azure::network network-cluster-example) + subnet: "subnet1" + maximum-pods-per-node: 110 + minimum-node-size: 1 + maximum-node-size: 5 + kubelet-disk-type: "OS" + + tags: { + Name: "agentpool_primary" + } + end + + network-profile + dns-service-ip: "10.0.0.10" + docker-bridge-cidr: "172.17.0.1/16" + service-cidr: "10.0.0.0/16" + load-balancer-sku: "standard" + outbound-type: "loadBalancer" + + load-balancer-profile + outbound-ips + public-ips: [ $(azure::public-ip-address public-ip-address-example-cluster) ] + end + + end + end + + tags: { + Name: "kubernetes-cluster-example" + } + + +end diff --git a/src/main/java/gyro/azure/containerservice/ClusterAddonProfile.java b/src/main/java/gyro/azure/containerservice/ClusterAddonProfile.java new file mode 100644 index 00000000..36a81071 --- /dev/null +++ b/src/main/java/gyro/azure/containerservice/ClusterAddonProfile.java @@ -0,0 +1,82 @@ +package gyro.azure.containerservice; + +import java.util.HashMap; +import java.util.Map; + +import com.azure.resourcemanager.containerservice.models.ManagedClusterAddonProfile; +import gyro.azure.Copyable; +import gyro.azure.identity.IdentityResource; +import gyro.core.resource.Diffable; +import gyro.core.resource.Updatable; +import gyro.core.validation.Required; + +public class ClusterAddonProfile extends Diffable implements Copyable { + + private Map config; + private IdentityResource identity; + private Boolean enabled; + + /** + * The config for the addon profile. + */ + @Required + @Updatable + public Map getConfig() { + if (config == null) { + config = new HashMap<>(); + } + + return config; + } + + public void setConfig(Map config) { + this.config = config; + } + + /** + * The identity for the addon profile. + */ + @Required + @Updatable + public IdentityResource getIdentity() { + return identity; + } + + public void setIdentity(IdentityResource identity) { + this.identity = identity; + } + + /** + * If set to ``true`` enables the addon profile. Defaults to``true``. + */ + @Updatable + public Boolean getEnabled() { + if (enabled == null) { + enabled = true; + } + + return enabled; + } + + public void setEnabled(Boolean enabled) { + this.enabled = enabled; + } + + @Override + public void copyFrom(ManagedClusterAddonProfile model) { + setConfig(model.config()); + setIdentity(findById(IdentityResource.class, model.identity() != null ? model.identity().resourceId() : null)); + setEnabled(model.enabled()); + } + + @Override + public String primaryKey() { + return ""; + } + + protected ManagedClusterAddonProfile toAddonProfile() { + return new ManagedClusterAddonProfile() + .withConfig(getConfig()) + .withEnabled(getEnabled()); + } +} diff --git a/src/main/java/gyro/azure/containerservice/ClusterAgentPool.java b/src/main/java/gyro/azure/containerservice/ClusterAgentPool.java new file mode 100644 index 00000000..e4023709 --- /dev/null +++ b/src/main/java/gyro/azure/containerservice/ClusterAgentPool.java @@ -0,0 +1,410 @@ +package gyro.azure.containerservice; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import com.azure.resourcemanager.containerservice.models.KubernetesClusterAgentPool; +import gyro.azure.Copyable; +import gyro.azure.network.NetworkResource; +import gyro.azure.network.SubnetResource; +import gyro.core.resource.Diffable; +import gyro.core.resource.Output; +import gyro.core.resource.Updatable; +import gyro.core.validation.DependsOn; +import gyro.core.validation.Required; +import gyro.core.validation.ValidStrings; + +public class ClusterAgentPool extends Diffable implements Copyable { + + private String name; + private String size; + private Integer count; + private List availabilityZones; + private Map tags; + private String mode; + private Boolean autoScalingEnabled; + private String kubeletDiskType; + private Integer maximumNodeSize; + private Integer minimumNodeSize; + private Integer maximumPodsPerNode; + private NetworkResource network; + private String subnet; + private Map nodeLabels; + private Integer nodeSize; + private List nodeTaints; + private Integer osDiskSizeInGb; + private String osDiskType; + private String osType; + private String powerState; + private String provisioningState; + private String type; + private String virtualMachineEvictionPolicy; + private Double virtualMachineMaximumPrice; + private String virtualMachinePriority; + + /** + * The name of the agent pool. + */ + @Required + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + /** + * The node size of the agent pool. + */ + @Required + public String getSize() { + return size; + } + + public void setSize(String size) { + this.size = size; + } + + /** + * The node count of the agent pool. + */ + @Required + @Updatable + public Integer getCount() { + return count; + } + + public void setCount(Integer count) { + this.count = count; + } + + /** + * A list of availability zones to start the agent pool node on. + */ + public List getAvailabilityZones() { + if (availabilityZones == null) { + availabilityZones = new ArrayList<>(); + } + + return availabilityZones; + } + + public void setAvailabilityZones(List availabilityZones) { + this.availabilityZones = availabilityZones; + } + + /** + * The tags of the agent pool. + */ + @Updatable + public Map getTags() { + if (tags == null) { + tags = new HashMap<>(); + } + + return tags; + } + + public void setTags(Map tags) { + this.tags = tags; + } + + /** + * The mode of the agent pool. + */ + @Required + @Updatable + @ValidStrings({"System", "User"}) + public String getMode() { + return mode; + } + + public void setMode(String mode) { + this.mode = mode; + } + + /** + * If set to ``true`` enables autoscaling. Defaults to ``false``. + */ + @Updatable + public Boolean getAutoScalingEnabled() { + if (autoScalingEnabled == null) { + autoScalingEnabled = false; + } + + return autoScalingEnabled; + } + + public void setAutoScalingEnabled(Boolean autoScalingEnabled) { + this.autoScalingEnabled = autoScalingEnabled; + } + + /** + * The kublet disk type for the agent pool. + */ + @Updatable + @ValidStrings({"OS", "Temporary"}) + public String getKubeletDiskType() { + return kubeletDiskType; + } + + public void setKubeletDiskType(String kubeletDiskType) { + this.kubeletDiskType = kubeletDiskType; + } + + /** + * The max node size for the agent pool. + */ + @Updatable + @DependsOn("auto-scaling-enabled") + public Integer getMaximumNodeSize() { + return maximumNodeSize; + } + + public void setMaximumNodeSize(Integer maximumNodeSize) { + this.maximumNodeSize = maximumNodeSize; + } + + /** + * The max node size for the agent pool. + */ + @Updatable + @DependsOn("auto-scaling-enabled") + public Integer getMinimumNodeSize() { + return minimumNodeSize; + } + + public void setMinimumNodeSize(Integer minimumNodeSize) { + this.minimumNodeSize = minimumNodeSize; + } + + /** + * The max pods per node for the agent pool. + */ + @Required + public Integer getMaximumPodsPerNode() { + return maximumPodsPerNode; + } + + public void setMaximumPodsPerNode(Integer maximumPodsPerNode) { + this.maximumPodsPerNode = maximumPodsPerNode; + } + + /** + * The network for the agent pool. + */ + @Required + public NetworkResource getNetwork() { + return network; + } + + + public void setNetwork(NetworkResource network) { + this.network = network; + } + + /** + * The subnet for the agent pool. + */ + @Required + public String getSubnet() { + return subnet; + } + + public void setSubnet(String subnet) { + this.subnet = subnet; + } + + /** + * The node labels for the agent pool. + */ + public Map getNodeLabels() { + if (nodeLabels == null) { + nodeLabels = new HashMap<>(); + } + + return nodeLabels; + } + + public void setNodeLabels(Map nodeLabels) { + this.nodeLabels = nodeLabels; + } + + /** + * The node size of the agent pool. + */ + @Output + public Integer getNodeSize() { + return nodeSize; + } + + public void setNodeSize(Integer nodeSize) { + this.nodeSize = nodeSize; + } + + /** + * The list of node taints of the agent pool. + */ + public List getNodeTaints() { + if (nodeTaints == null) { + nodeTaints = new ArrayList<>(); + } + + return nodeTaints; + } + + public void setNodeTaints(List nodeTaints) { + this.nodeTaints = nodeTaints; + } + + /** + * The os disk size of the agent pool. + */ + @Required + public Integer getOsDiskSizeInGb() { + return osDiskSizeInGb; + } + + public void setOsDiskSizeInGb(Integer osDiskSizeInGb) { + this.osDiskSizeInGb = osDiskSizeInGb; + } + + /** + * The os disk type of the agent pool. + */ + @Required + @ValidStrings({"Managed", "Ephemeral"}) + public String getOsDiskType() { + return osDiskType; + } + + public void setOsDiskType(String osDiskType) { + this.osDiskType = osDiskType; + } + + /** + * The OS type of the agent pool. + */ + @Required + @ValidStrings({"Linux", "Windows"}) + public String getOsType() { + return osType; + } + + public void setOsType(String osType) { + this.osType = osType; + } + + /** + * The power state of the agent pool. + */ + @Output + public String getPowerState() { + return powerState; + } + + public void setPowerState(String powerState) { + this.powerState = powerState; + } + + /** + * The provisioning state of the agent pool. + */ + @Output + public String getProvisioningState() { + return provisioningState; + } + + public void setProvisioningState(String provisioningState) { + this.provisioningState = provisioningState; + } + + /** + * The type of the agent pool. + */ + @Required + @ValidStrings({"VirtualMachineScaleSets", "AvailabilitySet"}) + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + /** + * The eviction policy of a spot instance for the node of the agent pool. + */ + @ValidStrings({"Delete", "Deallocate"}) + public String getVirtualMachineEvictionPolicy() { + return virtualMachineEvictionPolicy; + } + + public void setVirtualMachineEvictionPolicy(String virtualMachineEvictionPolicy) { + this.virtualMachineEvictionPolicy = virtualMachineEvictionPolicy; + } + + /** + * The max price for virtual machine for the node of the agent pool. + */ + @DependsOn("virtual-machine-eviction-policy") + public Double getVirtualMachineMaximumPrice() { + return virtualMachineMaximumPrice; + } + + public void setVirtualMachineMaximumPrice(Double virtualMachineMaximumPrice) { + this.virtualMachineMaximumPrice = virtualMachineMaximumPrice; + } + + /** + * The priority for virtual machine for the node of the agent pool. + */ + @DependsOn("virtual-machine-eviction-policy") + @ValidStrings({"Spot", "Regular"}) + public String getVirtualMachinePriority() { + return virtualMachinePriority; + } + + public void setVirtualMachinePriority(String virtualMachinePriority) { + this.virtualMachinePriority = virtualMachinePriority; + } + + @Override + public void copyFrom(KubernetesClusterAgentPool model) { + setName(model.name()); + setCount(model.count()); + setAvailabilityZones(model.availabilityZones().stream().map(Integer::valueOf).collect(Collectors.toList())); + setTags(model.tags()); + setMode(model.mode().toString()); + setAutoScalingEnabled(model.isAutoScalingEnabled()); + setKubeletDiskType(model.kubeletDiskType().toString()); + setMaximumNodeSize(model.maximumNodeSize()); + setMaximumPodsPerNode(model.maximumPodsPerNode()); + setMinimumNodeSize(model.minimumNodeSize()); + setNetwork(findById(NetworkResource.class, model.networkId())); + setNodeLabels(model.nodeLabels()); + setNodeSize(model.nodeSize()); + setNodeTaints(model.nodeTaints()); + setOsDiskSizeInGb(model.osDiskSizeInGB()); + setOsDiskType(model.osDiskType().toString()); + setOsType(model.osType().toString()); + setPowerState(model.powerState().code().toString()); + setProvisioningState(model.provisioningState()); + setSubnet(model.subnetName()); + setType(model.type().toString()); + setVirtualMachineEvictionPolicy(model.virtualMachineEvictionPolicy() != null ? model.virtualMachineEvictionPolicy().toString() : null); + setVirtualMachineMaximumPrice(model.innerModel().spotMaxPrice() != null ? model.virtualMachineMaximumPrice() : null); + setVirtualMachinePriority(model.virtualMachinePriority() != null ? model.virtualMachinePriority().toString() : null); + setSize(model.vmSize() != null ? model.vmSize().toString() : null); + + } + + @Override + public String primaryKey() { + return getName(); + } +} diff --git a/src/main/java/gyro/azure/containerservice/ClusterLoadBalancerManagedOutboundIps.java b/src/main/java/gyro/azure/containerservice/ClusterLoadBalancerManagedOutboundIps.java new file mode 100644 index 00000000..f1e8a012 --- /dev/null +++ b/src/main/java/gyro/azure/containerservice/ClusterLoadBalancerManagedOutboundIps.java @@ -0,0 +1,39 @@ +package gyro.azure.containerservice; + +import com.azure.resourcemanager.containerservice.models.ManagedClusterLoadBalancerProfileManagedOutboundIPs; +import gyro.azure.Copyable; +import gyro.core.resource.Diffable; +import gyro.core.resource.Updatable; +import gyro.core.validation.Required; + +public class ClusterLoadBalancerManagedOutboundIps extends Diffable implements Copyable { + + private Integer count; + + /** + * The count of managed outbound ips. + */ + @Required + @Updatable + public Integer getCount() { + return count; + } + + public void setCount(Integer count) { + this.count = count; + } + + @Override + public void copyFrom(ManagedClusterLoadBalancerProfileManagedOutboundIPs model) { + setCount(model.count()); + } + + @Override + public String primaryKey() { + return ""; + } + + protected ManagedClusterLoadBalancerProfileManagedOutboundIPs toManagedOutboundIps() { + return new ManagedClusterLoadBalancerProfileManagedOutboundIPs().withCount(getCount()); + } +} diff --git a/src/main/java/gyro/azure/containerservice/ClusterLoadBalancerOutboundIpPrefixes.java b/src/main/java/gyro/azure/containerservice/ClusterLoadBalancerOutboundIpPrefixes.java new file mode 100644 index 00000000..01dd2cb8 --- /dev/null +++ b/src/main/java/gyro/azure/containerservice/ClusterLoadBalancerOutboundIpPrefixes.java @@ -0,0 +1,52 @@ +package gyro.azure.containerservice; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +import com.azure.resourcemanager.containerservice.models.ManagedClusterLoadBalancerProfileOutboundIpPrefixes; +import com.azure.resourcemanager.containerservice.models.ResourceReference; +import gyro.azure.Copyable; +import gyro.core.resource.Diffable; +import gyro.core.resource.Updatable; +import gyro.core.validation.Required; + +public class ClusterLoadBalancerOutboundIpPrefixes extends Diffable implements Copyable { + + private List publicIpPrefixes; + + /** + * The count of public ip prefixes. + */ + @Required + @Updatable + public List getPublicIpPrefixes() { + if (publicIpPrefixes == null) { + publicIpPrefixes = new ArrayList<>(); + } + + return publicIpPrefixes; + } + + public void setPublicIpPrefixes(List publicIpPrefixes) { + this.publicIpPrefixes = publicIpPrefixes; + } + + @Override + public void copyFrom(ManagedClusterLoadBalancerProfileOutboundIpPrefixes model) { + setPublicIpPrefixes(model.publicIpPrefixes().stream().map(ResourceReference::id).collect(Collectors.toList())); + } + + @Override + public String primaryKey() { + return ""; + } + + protected ManagedClusterLoadBalancerProfileOutboundIpPrefixes toOutboundIpPrefixes() { + return new ManagedClusterLoadBalancerProfileOutboundIpPrefixes() + .withPublicIpPrefixes(getPublicIpPrefixes() + .stream() + .map(o -> new ResourceReference().withId(o)) + .collect(Collectors.toList())); + } +} diff --git a/src/main/java/gyro/azure/containerservice/ClusterLoadBalancerOutboundIps.java b/src/main/java/gyro/azure/containerservice/ClusterLoadBalancerOutboundIps.java new file mode 100644 index 00000000..44628c85 --- /dev/null +++ b/src/main/java/gyro/azure/containerservice/ClusterLoadBalancerOutboundIps.java @@ -0,0 +1,56 @@ +package gyro.azure.containerservice; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +import com.azure.resourcemanager.containerservice.models.ManagedClusterLoadBalancerProfileOutboundIPs; +import com.azure.resourcemanager.containerservice.models.ResourceReference; +import gyro.azure.Copyable; +import gyro.azure.network.PublicIpAddressResource; +import gyro.core.resource.Diffable; +import gyro.core.resource.Updatable; +import gyro.core.validation.Required; + +public class ClusterLoadBalancerOutboundIps extends Diffable implements Copyable { + + private List publicIps; + + /** + * The list of public ips. + */ + @Required + @Updatable + public List getPublicIps() { + if (publicIps == null) { + publicIps = new ArrayList<>(); + } + + return publicIps; + } + + public void setPublicIps(List publicIps) { + this.publicIps = publicIps; + } + + @Override + public void copyFrom(ManagedClusterLoadBalancerProfileOutboundIPs model) { + setPublicIps(model.publicIPs().stream() + .map(ResourceReference::id) + .map(id -> findById(PublicIpAddressResource.class, id)) + .collect(Collectors.toList())); + } + + @Override + public String primaryKey() { + return ""; + } + + protected ManagedClusterLoadBalancerProfileOutboundIPs toOutboundIPs() { + return new ManagedClusterLoadBalancerProfileOutboundIPs() + .withPublicIPs(getPublicIps() + .stream() + .map(o -> new ResourceReference().withId(o.getId())) + .collect(Collectors.toList())); + } +} diff --git a/src/main/java/gyro/azure/containerservice/ClusterLoadBalancerProfile.java b/src/main/java/gyro/azure/containerservice/ClusterLoadBalancerProfile.java new file mode 100644 index 00000000..97c7d281 --- /dev/null +++ b/src/main/java/gyro/azure/containerservice/ClusterLoadBalancerProfile.java @@ -0,0 +1,185 @@ +package gyro.azure.containerservice; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +import com.azure.resourcemanager.containerservice.models.ManagedClusterLoadBalancerProfile; +import com.azure.resourcemanager.containerservice.models.ResourceReference; +import gyro.azure.Copyable; +import gyro.core.resource.Diffable; +import gyro.core.resource.Updatable; + +public class ClusterLoadBalancerProfile extends Diffable implements Copyable { + + private Integer allocatedOutboundPorts; + private List effectiveOutboundIps; + private Boolean enableMultipleStandardLoadBalancers; + private Integer idleTimeoutInMinutes; + private ClusterLoadBalancerManagedOutboundIps managedOutboundIps; + private ClusterLoadBalancerOutboundIpPrefixes outboundIpPrefixes; + private ClusterLoadBalancerOutboundIps outboundIps; + + /** + * The allocated outbound ports for the load balancer profile. + */ + public Integer getAllocatedOutboundPorts() { + return allocatedOutboundPorts; + } + + public void setAllocatedOutboundPorts(Integer allocatedOutboundPorts) { + this.allocatedOutboundPorts = allocatedOutboundPorts; + } + + /** + * A list of effective outbound ips for the load balancer profile. + */ + public List getEffectiveOutboundIps() { + if (effectiveOutboundIps == null) { + effectiveOutboundIps = new ArrayList<>(); + } + + return effectiveOutboundIps; + } + + public void setEffectiveOutboundIps(List effectiveOutboundIps) { + this.effectiveOutboundIps = effectiveOutboundIps; + } + + /** + * If set to ``true`` enables multiple standard load balancer. Defaults to ``false``. + */ + public Boolean getEnableMultipleStandardLoadBalancers() { + if (enableMultipleStandardLoadBalancers == null) { + enableMultipleStandardLoadBalancers = false; + } + + return enableMultipleStandardLoadBalancers; + } + + public void setEnableMultipleStandardLoadBalancers(Boolean enableMultipleStandardLoadBalancers) { + this.enableMultipleStandardLoadBalancers = enableMultipleStandardLoadBalancers; + } + + /** + * The idle timeouts in minutes for the load balancer profile. + */ + public Integer getIdleTimeoutInMinutes() { + return idleTimeoutInMinutes; + } + + public void setIdleTimeoutInMinutes(Integer idleTimeoutInMinutes) { + this.idleTimeoutInMinutes = idleTimeoutInMinutes; + } + + /** + * The managed outbound ip config for the load balancer profile. + * + * @subresource gyro.azure.containerservice.ClusterLoadBalancerManagedOutboundIps + */ + @Updatable + public ClusterLoadBalancerManagedOutboundIps getManagedOutboundIps() { + return managedOutboundIps; + } + + public void setManagedOutboundIPs(ClusterLoadBalancerManagedOutboundIps managedOutboundIps) { + this.managedOutboundIps = managedOutboundIps; + } + + /** + * The load balancer outbound ip prefixes config for the load balancer profile. + * + * @subresource gyro.azure.containerservice.ClusterLoadBalancerOutboundIpPrefixes + */ + @Updatable + public ClusterLoadBalancerOutboundIpPrefixes getOutboundIpPrefixes() { + return outboundIpPrefixes; + } + + public void setOutboundIpPrefixes(ClusterLoadBalancerOutboundIpPrefixes outboundIpPrefixes) { + this.outboundIpPrefixes = outboundIpPrefixes; + } + + /** + * The load balancer outbound ips config for the load balancer profile. + * + * @subresource gyro.azure.containerservice.ClusterLoadBalancerOutboundIps + */ + @Updatable + public ClusterLoadBalancerOutboundIps getOutboundIps() { + return outboundIps; + } + + public void setOutboundIps(ClusterLoadBalancerOutboundIps outboundIps) { + this.outboundIps = outboundIps; + } + + @Override + public void copyFrom(ManagedClusterLoadBalancerProfile model) { + setAllocatedOutboundPorts(model.allocatedOutboundPorts()); + setEffectiveOutboundIps(model.effectiveOutboundIPs().stream().map(ResourceReference::id).collect(Collectors.toList())); + setEnableMultipleStandardLoadBalancers(model.enableMultipleStandardLoadBalancers()); + setIdleTimeoutInMinutes(model.idleTimeoutInMinutes()); + + ClusterLoadBalancerManagedOutboundIps managedOutboundIps = null; + if (model.managedOutboundIPs() != null) { + managedOutboundIps = newSubresource(ClusterLoadBalancerManagedOutboundIps.class); + managedOutboundIps.copyFrom(model.managedOutboundIPs()); + } + setManagedOutboundIPs(managedOutboundIps); + + ClusterLoadBalancerOutboundIps outboundIps = null; + if (model.outboundIPs() != null) { + outboundIps = newSubresource(ClusterLoadBalancerOutboundIps.class); + outboundIps.copyFrom(model.outboundIPs()); + } + setOutboundIps(outboundIps); + + ClusterLoadBalancerOutboundIpPrefixes outboundIpPrefixes = null; + if (model.outboundIpPrefixes() != null) { + outboundIpPrefixes = newSubresource(ClusterLoadBalancerOutboundIpPrefixes.class); + outboundIpPrefixes.copyFrom(model.outboundIpPrefixes()); + } + setOutboundIpPrefixes(outboundIpPrefixes); + } + + @Override + public String primaryKey() { + return ""; + } + + protected ManagedClusterLoadBalancerProfile toClusterLoadBalancerProfile() { + ManagedClusterLoadBalancerProfile profile = new ManagedClusterLoadBalancerProfile(); + + if (getAllocatedOutboundPorts() != null) { + profile.withAllocatedOutboundPorts(getAllocatedOutboundPorts()); + } + + profile.withEnableMultipleStandardLoadBalancers(getEnableMultipleStandardLoadBalancers()); + + if (getIdleTimeoutInMinutes() != null) { + profile.withIdleTimeoutInMinutes(getIdleTimeoutInMinutes()); + } + + if (getManagedOutboundIps() != null) { + profile.withManagedOutboundIPs(getManagedOutboundIps().toManagedOutboundIps()); + } + + if (getOutboundIpPrefixes() != null) { + profile.withOutboundIpPrefixes(getOutboundIpPrefixes().toOutboundIpPrefixes()); + } + + if (getOutboundIps() != null) { + profile.withOutboundIPs(getOutboundIps().toOutboundIPs()); + } + + if (getEffectiveOutboundIps().isEmpty()) { + profile.withEffectiveOutboundIPs(getEffectiveOutboundIps() + .stream() + .map(o -> new ResourceReference().withId(o)) + .collect(Collectors.toList())); + } + + return profile; + } +} diff --git a/src/main/java/gyro/azure/containerservice/ClusterManagedOutboundIpProfile.java b/src/main/java/gyro/azure/containerservice/ClusterManagedOutboundIpProfile.java new file mode 100644 index 00000000..35bd77fe --- /dev/null +++ b/src/main/java/gyro/azure/containerservice/ClusterManagedOutboundIpProfile.java @@ -0,0 +1,37 @@ +package gyro.azure.containerservice; + +import com.azure.resourcemanager.containerservice.models.ManagedClusterManagedOutboundIpProfile; +import gyro.azure.Copyable; +import gyro.core.resource.Diffable; +import gyro.core.validation.Required; + +public class ClusterManagedOutboundIpProfile extends Diffable implements Copyable { + + private Integer count; + + /** + * The desired number of outbound IPs created/managed by Azure. + */ + @Required + public Integer getCount() { + return count; + } + + public void setCount(Integer count) { + this.count = count; + } + + @Override + public void copyFrom(ManagedClusterManagedOutboundIpProfile model) { + setCount(model.count()); + } + + @Override + public String primaryKey() { + return getCount().toString(); + } + + protected ManagedClusterManagedOutboundIpProfile toOutboundIpProfile() { + return new ManagedClusterManagedOutboundIpProfile().withCount(getCount()); + } +} diff --git a/src/main/java/gyro/azure/containerservice/ClusterNatGatewayProfile.java b/src/main/java/gyro/azure/containerservice/ClusterNatGatewayProfile.java new file mode 100644 index 00000000..165fd456 --- /dev/null +++ b/src/main/java/gyro/azure/containerservice/ClusterNatGatewayProfile.java @@ -0,0 +1,102 @@ +package gyro.azure.containerservice; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +import com.azure.resourcemanager.containerservice.models.ManagedClusterNatGatewayProfile; +import com.azure.resourcemanager.containerservice.models.ResourceReference; +import gyro.azure.Copyable; +import gyro.core.resource.Diffable; +import gyro.core.validation.Required; + +public class ClusterNatGatewayProfile extends Diffable implements Copyable { + + private List effectiveOutboundIps; + private Integer idleTimeoutInMinutes; + private ClusterManagedOutboundIpProfile managedOutboundIpProfile; + + /** + * A list of effective outbound ips for the nat gateway profile. + */ + public List getEffectiveOutboundIps() { + if (effectiveOutboundIps == null) { + effectiveOutboundIps = new ArrayList<>(); + } + + return effectiveOutboundIps; + } + + public void setEffectiveOutboundIps(List effectiveOutboundIps) { + this.effectiveOutboundIps = effectiveOutboundIps; + } + + /** + * Idle timeout in minutes in for the nat gateway profile. + */ + @Required + public Integer getIdleTimeoutInMinutes() { + return idleTimeoutInMinutes; + } + + public void setIdleTimeoutInMinutes(Integer idleTimeoutInMinutes) { + this.idleTimeoutInMinutes = idleTimeoutInMinutes; + } + + /** + * The managed outbound ip profile config for the nat gateway profile. + * + * @subresource gyro.azure.containerservice.ClusterManagedOutboundIpProfile + */ + public ClusterManagedOutboundIpProfile getManagedOutboundIpProfile() { + return managedOutboundIpProfile; + } + + public void setManagedOutboundIpProfile(ClusterManagedOutboundIpProfile managedOutboundIpProfile) { + this.managedOutboundIpProfile = managedOutboundIpProfile; + } + + @Override + public void copyFrom(ManagedClusterNatGatewayProfile model) { + setEffectiveOutboundIps(model.effectiveOutboundIPs() != null + ? model.effectiveOutboundIPs().stream() + .map(ResourceReference::id) + .collect(Collectors.toList()) + : null); + + setIdleTimeoutInMinutes(model.idleTimeoutInMinutes()); + + ClusterManagedOutboundIpProfile managedOutboundIpProfile = null; + if (model.managedOutboundIpProfile() != null) { + managedOutboundIpProfile = newSubresource(ClusterManagedOutboundIpProfile.class); + managedOutboundIpProfile.copyFrom(model.managedOutboundIpProfile()); + } + setManagedOutboundIpProfile(managedOutboundIpProfile); + } + + @Override + public String primaryKey() { + return ""; + } + + protected ManagedClusterNatGatewayProfile toNatGatewayProfile() { + ManagedClusterNatGatewayProfile profile = new ManagedClusterNatGatewayProfile(); + + if (!getEffectiveOutboundIps().isEmpty()) { + profile.withEffectiveOutboundIPs(getEffectiveOutboundIps() + .stream() + .map(o -> new ResourceReference().withId(o)) + .collect(Collectors.toList())); + } + + if (getIdleTimeoutInMinutes() != null) { + profile.withIdleTimeoutInMinutes(getIdleTimeoutInMinutes()); + } + + if (getManagedOutboundIpProfile() != null) { + profile.withManagedOutboundIpProfile(getManagedOutboundIpProfile().toOutboundIpProfile()); + } + + return profile; + } +} diff --git a/src/main/java/gyro/azure/containerservice/ClusterPropertiesAutoScalerProfile.java b/src/main/java/gyro/azure/containerservice/ClusterPropertiesAutoScalerProfile.java new file mode 100644 index 00000000..18d2d695 --- /dev/null +++ b/src/main/java/gyro/azure/containerservice/ClusterPropertiesAutoScalerProfile.java @@ -0,0 +1,318 @@ +package gyro.azure.containerservice; + +import com.azure.resourcemanager.containerservice.models.Expander; +import com.azure.resourcemanager.containerservice.models.ManagedClusterPropertiesAutoScalerProfile; +import gyro.azure.Copyable; +import gyro.core.resource.Diffable; +import gyro.core.resource.Updatable; +import gyro.core.validation.Required; +import gyro.core.validation.ValidStrings; + +public class ClusterPropertiesAutoScalerProfile extends Diffable implements Copyable { + + private String expander; + private String balanceSimilarNodeGroups; + private String maxEmptyBulkDelete; + private String maxGracefulTerminationSec; + private String maxTotalUnreadyPercentage; + private String newPodScaleUpDelay; + private String okTotalUnreadyCount; + private String scaleDownDelayAfterAdd; + private String scaleDownDelayAfterDelete; + private String scaleDownDelayAfterFailure; + private String scaleDownUnreadyTime; + private String scaleDownUnneededTime; + private String scaleDownUtilizationThreshold; + private String scanInterval; + private String skipNodesWithSystemPods; + private String skipNodesWithLocalStorage; + + /** + * The expander for the autoscaler profile. + */ + @Required + @Updatable + @ValidStrings({"least-waste", "most-pods", "priority", "random"}) + public String getExpander() { + return expander; + } + + public void setExpander(String expander) { + this.expander = expander; + } + + /** + * The balance similar node groups for the autoscaler profile. + */ + @Updatable + public String getBalanceSimilarNodeGroups() { + return balanceSimilarNodeGroups; + } + + public void setBalanceSimilarNodeGroups(String balanceSimilarNodeGroups) { + this.balanceSimilarNodeGroups = balanceSimilarNodeGroups; + } + + /** + * The max empty bulk delete for the autoscaler profile. + */ + @Updatable + public String getMaxEmptyBulkDelete() { + return maxEmptyBulkDelete; + } + + public void setMaxEmptyBulkDelete(String maxEmptyBulkDelete) { + this.maxEmptyBulkDelete = maxEmptyBulkDelete; + } + + /** + * The max graceful termination sec for the autoscaler profile. + */ + @Updatable + public String getMaxGracefulTerminationSec() { + return maxGracefulTerminationSec; + } + + public void setMaxGracefulTerminationSec(String maxGracefulTerminationSec) { + this.maxGracefulTerminationSec = maxGracefulTerminationSec; + } + + /** + * The max total unready percentage for the autoscaler profile. + */ + @Updatable + public String getMaxTotalUnreadyPercentage() { + return maxTotalUnreadyPercentage; + } + + public void setMaxTotalUnreadyPercentage(String maxTotalUnreadyPercentage) { + this.maxTotalUnreadyPercentage = maxTotalUnreadyPercentage; + } + + /** + * The new pod scale up delay for the autoscaler profile. + */ + @Updatable + public String getNewPodScaleUpDelay() { + return newPodScaleUpDelay; + } + + public void setNewPodScaleUpDelay(String newPodScaleUpDelay) { + this.newPodScaleUpDelay = newPodScaleUpDelay; + } + + /** + * The ok total unready count for the autoscaler profile. + */ + @Updatable + public String getOkTotalUnreadyCount() { + return okTotalUnreadyCount; + } + + public void setOkTotalUnreadyCount(String okTotalUnreadyCount) { + this.okTotalUnreadyCount = okTotalUnreadyCount; + } + + /** + * The scale down delay after add for the autoscaler profile. Values must be an integer followed by an 'm'. No unit of time other than minutes (m) is supported. + */ + @Updatable + public String getScaleDownDelayAfterAdd() { + return scaleDownDelayAfterAdd; + } + + public void setScaleDownDelayAfterAdd(String scaleDownDelayAfterAdd) { + this.scaleDownDelayAfterAdd = scaleDownDelayAfterAdd; + } + + /** + * The scale down delay after delete for the autoscaler profile. Values must be an integer followed by an 'm'. No unit of time other than minutes (m) is supported. + */ + @Updatable + public String getScaleDownDelayAfterDelete() { + return scaleDownDelayAfterDelete; + } + + public void setScaleDownDelayAfterDelete(String scaleDownDelayAfterDelete) { + this.scaleDownDelayAfterDelete = scaleDownDelayAfterDelete; + } + + /** + * The scale down delay after failure for the autoscaler profile. Values must be an integer followed by an 'm'. No unit of time other than minutes (m) is supported. + */ + @Updatable + public String getScaleDownDelayAfterFailure() { + return scaleDownDelayAfterFailure; + } + + public void setScaleDownDelayAfterFailure(String scaleDownDelayAfterFailure) { + this.scaleDownDelayAfterFailure = scaleDownDelayAfterFailure; + } + + /** + * The scale down unready time for the autoscaler profile. + */ + @Updatable + public String getScaleDownUnreadyTime() { + return scaleDownUnreadyTime; + } + + public void setScaleDownUnreadyTime(String scaleDownUnreadyTime) { + this.scaleDownUnreadyTime = scaleDownUnreadyTime; + } + + /** + * The scale down unneeded time for the autoscaler profile. + */ + @Updatable + public String getScaleDownUnneededTime() { + return scaleDownUnneededTime; + } + + public void setScaleDownUnneededTime(String scaleDownUnneededTime) { + this.scaleDownUnneededTime = scaleDownUnneededTime; + } + + /** + * The scale down utilization threshold for the autoscaler profile. + */ + @Updatable + public String getScaleDownUtilizationThreshold() { + return scaleDownUtilizationThreshold; + } + + public void setScaleDownUtilizationThreshold(String scaleDownUtilizationThreshold) { + this.scaleDownUtilizationThreshold = scaleDownUtilizationThreshold; + } + + /** + * The scan interval for the autoscaler profile. + */ + @Updatable + public String getScanInterval() { + return scanInterval; + } + + public void setScanInterval(String scanInterval) { + this.scanInterval = scanInterval; + } + + /** + * The skip nodes with system pods for the autoscaler profile. + */ + @Updatable + public String getSkipNodesWithSystemPods() { + return skipNodesWithSystemPods; + } + + public void setSkipNodesWithSystemPods(String skipNodesWithSystemPods) { + this.skipNodesWithSystemPods = skipNodesWithSystemPods; + } + + /** + * The skip nodes with local storage for the autoscaler profile. + */ + @Updatable + public String getSkipNodesWithLocalStorage() { + return skipNodesWithLocalStorage; + } + + public void setSkipNodesWithLocalStorage(String skipNodesWithLocalStorage) { + this.skipNodesWithLocalStorage = skipNodesWithLocalStorage; + } + + @Override + public void copyFrom(ManagedClusterPropertiesAutoScalerProfile model) { + setExpander(model.expander().toString()); + setBalanceSimilarNodeGroups(model.balanceSimilarNodeGroups()); + setMaxEmptyBulkDelete(model.maxEmptyBulkDelete()); + setMaxGracefulTerminationSec(model.maxGracefulTerminationSec()); + setMaxTotalUnreadyPercentage(model.maxTotalUnreadyPercentage()); + setNewPodScaleUpDelay(model.newPodScaleUpDelay()); + setOkTotalUnreadyCount(model.okTotalUnreadyCount()); + setScaleDownDelayAfterAdd(model.scaleDownDelayAfterAdd()); + setScaleDownDelayAfterDelete(model.scaleDownDelayAfterDelete()); + setScaleDownDelayAfterFailure(model.scaleDownDelayAfterFailure()); + setScaleDownUnreadyTime(model.scaleDownUnreadyTime()); + setScaleDownUnneededTime(model.scaleDownUnneededTime()); + setScaleDownUtilizationThreshold(model.scaleDownUtilizationThreshold()); + setScanInterval(model.scanInterval()); + setSkipNodesWithSystemPods(model.skipNodesWithSystemPods()); + setSkipNodesWithLocalStorage(model.skipNodesWithLocalStorage()); + } + + @Override + public String primaryKey() { + return ""; + } + + protected ManagedClusterPropertiesAutoScalerProfile toAutoScalerProfile() { + ManagedClusterPropertiesAutoScalerProfile profile = new ManagedClusterPropertiesAutoScalerProfile(); + + if (getExpander() != null) { + profile.withExpander(Expander.fromString(getExpander())); + } + + if (getBalanceSimilarNodeGroups() != null) { + profile.withBalanceSimilarNodeGroups(getBalanceSimilarNodeGroups()); + } + + if (getMaxEmptyBulkDelete() != null) { + profile.withMaxEmptyBulkDelete(getMaxEmptyBulkDelete()); + } + + if (getMaxGracefulTerminationSec() != null) { + profile.withMaxGracefulTerminationSec(getMaxGracefulTerminationSec()); + } + + if (getMaxTotalUnreadyPercentage() != null) { + profile.withMaxTotalUnreadyPercentage(getMaxTotalUnreadyPercentage()); + } + + if (getNewPodScaleUpDelay() != null) { + profile.withNewPodScaleUpDelay(getNewPodScaleUpDelay()); + } + + if (getOkTotalUnreadyCount() != null) { + profile.withOkTotalUnreadyCount(getOkTotalUnreadyCount()); + } + + if (getScaleDownDelayAfterAdd() != null) { + profile.withScaleDownDelayAfterAdd(getScaleDownDelayAfterAdd()); + } + + if (getScaleDownDelayAfterDelete() != null) { + profile.withScaleDownDelayAfterDelete(getScaleDownDelayAfterDelete()); + } + + if (getScaleDownDelayAfterFailure() != null) { + profile.withScaleDownDelayAfterFailure(getScaleDownDelayAfterFailure()); + } + + if (getScaleDownUnreadyTime() != null) { + profile.withScaleDownUnreadyTime(getScaleDownUnreadyTime()); + } + + if (getScaleDownUnneededTime() != null) { + profile.withScaleDownUnneededTime(getScaleDownUnneededTime()); + } + + if (getScaleDownUtilizationThreshold() != null) { + profile.withScaleDownUtilizationThreshold(getScaleDownUtilizationThreshold()); + } + + if (getScanInterval() != null) { + profile.withScanInterval(getScanInterval()); + } + + if (getSkipNodesWithSystemPods() != null) { + profile.withSkipNodesWithSystemPods(getSkipNodesWithSystemPods()); + } + + if (getSkipNodesWithLocalStorage() != null) { + profile.withSkipNodesWithLocalStorage(getSkipNodesWithLocalStorage()); + } + + return profile; + } +} diff --git a/src/main/java/gyro/azure/containerservice/KubernetesClusterFinder.java b/src/main/java/gyro/azure/containerservice/KubernetesClusterFinder.java new file mode 100644 index 00000000..29109bce --- /dev/null +++ b/src/main/java/gyro/azure/containerservice/KubernetesClusterFinder.java @@ -0,0 +1,58 @@ +package gyro.azure.containerservice; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.containerservice.models.KubernetesCluster; +import gyro.azure.AzureResourceManagerFinder; +import gyro.core.Type; + +/** + * Query kubernetes-cluster. + * + * Example + * ------- + * + * .. code-block:: gyro + * + * kubernetes-cluster: $(external-query azure::kubernetes-cluster {}) + */ +@Type("kubernetes-cluster") +public class KubernetesClusterFinder extends AzureResourceManagerFinder { + + private String id; + + /** + * The id of the kubernetes cluster. + */ + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + @Override + protected List findAllAzure(AzureResourceManager client) { + return client.kubernetesClusters().list().stream().collect(Collectors.toList()); + } + + @Override + protected List findAzure( + AzureResourceManager client, Map filters) { + + List clusters= new ArrayList<>(); + + KubernetesCluster cluster = client.kubernetesClusters().getById(filters.get("id")); + + if (cluster != null) { + clusters.add(cluster); + } + + return clusters; + } +} diff --git a/src/main/java/gyro/azure/containerservice/KubernetesClusterResource.java b/src/main/java/gyro/azure/containerservice/KubernetesClusterResource.java new file mode 100644 index 00000000..d22d7286 --- /dev/null +++ b/src/main/java/gyro/azure/containerservice/KubernetesClusterResource.java @@ -0,0 +1,721 @@ +package gyro.azure.containerservice; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import com.azure.core.management.Region; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.containerservice.models.AgentPoolMode; +import com.azure.resourcemanager.containerservice.models.AgentPoolType; +import com.azure.resourcemanager.containerservice.models.ContainerServiceVMSizeTypes; +import com.azure.resourcemanager.containerservice.models.KubeletDiskType; +import com.azure.resourcemanager.containerservice.models.KubernetesCluster; +import com.azure.resourcemanager.containerservice.models.KubernetesClusterAgentPool; +import com.azure.resourcemanager.containerservice.models.KubernetesClusters; +import com.azure.resourcemanager.containerservice.models.ManagedClusterAddonProfile; +import com.azure.resourcemanager.containerservice.models.OSDiskType; +import com.azure.resourcemanager.containerservice.models.OSType; +import com.azure.resourcemanager.containerservice.models.PublicNetworkAccess; +import com.azure.resourcemanager.containerservice.models.ScaleSetEvictionPolicy; +import com.azure.resourcemanager.containerservice.models.ScaleSetPriority; +import com.azure.resourcemanager.containerservice.models.KubernetesClusterAgentPool.DefinitionStages.WithAttach; +import com.azure.resourcemanager.containerservice.models.KubernetesClusterAgentPool.DefinitionStages.Blank; +import com.azure.resourcemanager.containerservice.models.KubernetesCluster.DefinitionStages.WithCreate; +import com.azure.resourcemanager.containerservice.models.KubernetesCluster.DefinitionStages.WithServicePrincipalClientId; +import com.azure.resourcemanager.containerservice.models.KubernetesCluster.DefinitionStages.WithAgentPool; +import gyro.azure.AzureResource; +import gyro.azure.Copyable; +import gyro.azure.resources.ResourceGroupResource; +import gyro.core.GyroUI; +import gyro.core.Type; +import gyro.core.resource.Id; +import gyro.core.resource.Output; +import gyro.core.resource.Resource; +import gyro.core.resource.Updatable; +import gyro.core.scope.State; +import gyro.core.validation.CollectionMin; +import gyro.core.validation.Required; +import org.apache.commons.lang3.StringUtils; + +/** + * Creates a Identity. + * + * Example + * ------- + * + * .. code-block:: gyro + * + * azure::kubernetes-cluster kubernetes-cluster-example + * name: "kubernetes-cluster-example" + * version: "1.22.4" + * enable-private-cluster: false + * + * resource-group: $(azure::resource-group resource-group-cluster-example) + * + * linux-root-username: "adminuser" + * + * dns-prefix: "kubernetes-cluster-example-dns" + * enable-rbac: true + * + * agent-pool + * name: "agentpool" + * size: "Standard_DS2_v2" + * count: 1 + * availability-zones: [1,2,3] + * mode: "System" + * auto-scaling-enabled: true + * type: "VirtualMachineScaleSets" + * os-type: "Linux" + * os-disk-type: "Manged" + * os-disk-size-in-gb: 128 + * node-size: 1 + * network: $(azure::network network-cluster-example) + * subnet: "subnet1" + * maximum-pods-per-node: 110 + * minimum-node-size: 1 + * maximum-node-size: 5 + * kubelet-disk-type: "OS" + * + * tags: { + * Name: "agentpool_primary" + * } + * end + * + * network-profile + * dns-service-ip: "10.0.0.10" + * docker-bridge-cidr: "172.17.0.1/16" + * service-cidr: "10.0.0.0/16" + * load-balancer-sku: "Standard" + * outbound-type: "loadBalancer" + * + * load-balancer-profile + * outbound-ips + * public-ips: $(azure::public-ip-address public-ip-address-example-cluster) + * end + * + * end + * end + * + * tags: { + * Name: "kubernetes-cluster-example" + * } + * + * + * end + * + * + * + * + */ +@Type("kubernetes-cluster") +public class KubernetesClusterResource extends AzureResource implements Copyable { + + private String name; + private String version; + private Set addonProfile; + private Set agentPool; + private NetworkProfile networkProfile; + private String dnsPrefix; + private Boolean enableRbac; + private String fqdn; + private String linuxRootUsername; + private String nodeResourceGroup; + private String powerState; + private String provisioningState; + private String servicePrincipalClientId; + private String servicePrincipalSecret; + private String sshKey; + private String systemAssignedManagedServiceIdentityPrincipalId; + private String id; + private ResourceGroupResource resourceGroup; + private Map tags; + private Boolean enablePrivateCluster; + private ClusterPropertiesAutoScalerProfile autoScalerProfile; + + /** + * Name of the cluster. + */ + @Id + @Required + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + /** + * Version of the AKS cluster to use. + */ + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + /** + * Addon profile configuration. + * + * @subresource gyro.azure.containerservice.ClusterAddonProfile + */ + @Updatable + public Set getAddonProfile() { + if (addonProfile == null) { + addonProfile = new HashSet<>(); + } + + return addonProfile; + } + + public void setAddonProfile(Set addonProfile) { + this.addonProfile = addonProfile; + } + + /** + * Agent pool configuration. + * + * @subresource gyro.azure.containerservice.ClusterAgentPool + */ + @Required + @Updatable + @CollectionMin(1) + public Set getAgentPool() { + if (agentPool == null) { + agentPool = new HashSet<>(); + } + + return agentPool; + } + + public void setAgentPool(Set agentPool) { + this.agentPool = agentPool; + } + + /** + * Network Profile configuration. + * + * @subresource gyro.azure.containerservice.NetworkProfile + */ + @Updatable + public NetworkProfile getNetworkProfile() { + return networkProfile; + } + + public void setNetworkProfile(NetworkProfile networkProfile) { + this.networkProfile = networkProfile; + } + + /** + * The dns prefix for the cluster. + */ + public String getDnsPrefix() { + return dnsPrefix; + } + + public void setDnsPrefix(String dnsPrefix) { + this.dnsPrefix = dnsPrefix; + } + + /** + * When set to ``true`` enables rbac for the cluster. Defaults to ``true``. + */ + @Updatable + public Boolean getEnableRbac() { + if (enableRbac == null) { + enableRbac = true; + } + + return enableRbac; + } + + public void setEnableRbac(Boolean enableRbac) { + this.enableRbac = enableRbac; + } + + /** + * The fqdn for the cluster. + */ + @Output + public String getFqdn() { + return fqdn; + } + + public void setFqdn(String fqdn) { + this.fqdn = fqdn; + } + + /** + * The root user name. + */ + @Required + public String getLinuxRootUsername() { + return linuxRootUsername; + } + + public void setLinuxRootUsername(String linuxRootUsername) { + this.linuxRootUsername = linuxRootUsername; + } + + public String getNodeResourceGroup() { + return nodeResourceGroup; + } + + public void setNodeResourceGroup(String nodeResourceGroup) { + this.nodeResourceGroup = nodeResourceGroup; + } + + public String getPowerState() { + return powerState; + } + + public void setPowerState(String powerState) { + this.powerState = powerState; + } + + public String getProvisioningState() { + return provisioningState; + } + + public void setProvisioningState(String provisioningState) { + this.provisioningState = provisioningState; + } + + /** + * The service principal client id for the cluster. + */ + public String getServicePrincipalClientId() { + return servicePrincipalClientId; + } + + public void setServicePrincipalClientId(String servicePrincipalClientId) { + this.servicePrincipalClientId = servicePrincipalClientId; + } + + /** + * The service principal secret for the cluster. + */ + public String getServicePrincipalSecret() { + return servicePrincipalSecret; + } + + public void setServicePrincipalSecret(String servicePrincipalSecret) { + this.servicePrincipalSecret = servicePrincipalSecret; + } + + /** + * The ssh key for the cluster. + */ + @Required + public String getSshKey() { + return sshKey; + } + + public void setSshKey(String sshKey) { + this.sshKey = sshKey; + } + + /** + * The system assigned service principal id for the cluster. + */ + @Output + public String getSystemAssignedManagedServiceIdentityPrincipalId() { + return systemAssignedManagedServiceIdentityPrincipalId; + } + + public void setSystemAssignedManagedServiceIdentityPrincipalId(String systemAssignedManagedServiceIdentityPrincipalId) { + this.systemAssignedManagedServiceIdentityPrincipalId = systemAssignedManagedServiceIdentityPrincipalId; + } + + /** + * The id of the cluster. + */ + @Output + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + /** + * The resource group where the cluster will belong. + */ + @Required + public ResourceGroupResource getResourceGroup() { + return resourceGroup; + } + + public void setResourceGroup(ResourceGroupResource resourceGroup) { + this.resourceGroup = resourceGroup; + } + + /** + * The tags for the cluster. + */ + @Updatable + public Map getTags() { + if (tags == null) { + tags = new HashMap<>(); + } + + return tags; + } + + public void setTags(Map tags) { + this.tags = tags; + } + + /** + * If set to ``true`` makes the cluster private. Defaults to ``false``. + */ + public Boolean getEnablePrivateCluster() { + if (enablePrivateCluster == null) { + enablePrivateCluster = false; + } + + return enablePrivateCluster; + } + + public void setEnablePrivateCluster(Boolean enablePrivateCluster) { + this.enablePrivateCluster = enablePrivateCluster; + } + + /** + * Autoscaler profile config. + * + * @subresource gyro.azure.containerservice.ClusterPropertiesAutoScalerProfile + */ + @Updatable + public ClusterPropertiesAutoScalerProfile getAutoScalerProfile() { + return autoScalerProfile; + } + + public void setAutoScalerProfile(ClusterPropertiesAutoScalerProfile autoScalerProfile) { + this.autoScalerProfile = autoScalerProfile; + } + + @Override + public void copyFrom(KubernetesCluster cluster) { + setName(cluster.name()); + setVersion(cluster.version()); + setDnsPrefix(cluster.dnsPrefix()); + setEnableRbac(cluster.enableRBAC()); + setFqdn(cluster.fqdn()); + setLinuxRootUsername(cluster.linuxRootUsername()); + setNodeResourceGroup(cluster.nodeResourceGroup()); + setPowerState(cluster.powerState().toString()); + setProvisioningState(cluster.provisioningState()); + setServicePrincipalClientId(cluster.servicePrincipalClientId()); + setServicePrincipalSecret(cluster.servicePrincipalSecret()); + setSshKey(cluster.sshKey()); + setSystemAssignedManagedServiceIdentityPrincipalId(cluster.systemAssignedManagedServiceIdentityPrincipalId()); + setId(cluster.id()); + setResourceGroup(findById(ResourceGroupResource.class, cluster.resourceGroupName())); + setTags(cluster.tags()); + setEnablePrivateCluster(cluster.innerModel().publicNetworkAccess() != null ? cluster.innerModel().publicNetworkAccess().equals(PublicNetworkAccess.DISABLED) : null); + + + Set addonProfiles = new HashSet<>(); + try { + if (cluster.addonProfiles() != null) { + ClusterAddonProfile addonProfile; + for (ManagedClusterAddonProfile addon : cluster.addonProfiles().values()) { + addonProfile = newSubresource(ClusterAddonProfile.class); + addonProfile.copyFrom(addon); + addonProfiles.add(addonProfile); + } + } + } catch (NullPointerException ex) { + // ignore + // TODO cluster.addonProfiles() throwing npe + } + setAddonProfile(addonProfiles); + + Set agentPools = new HashSet<>(); + if (cluster.agentPools() != null) { + ClusterAgentPool agentPool; + for (KubernetesClusterAgentPool agent : cluster.agentPools().values()) { + agentPool = newSubresource(ClusterAgentPool.class); + agentPool.copyFrom(agent); + agentPools.add(agentPool); + } + } + setAgentPool(agentPools); + + NetworkProfile networkProfile = null; + if (cluster.networkProfile() != null) { + networkProfile = newSubresource(NetworkProfile.class); + networkProfile.copyFrom(cluster.networkProfile()); + } + setNetworkProfile(networkProfile); + + ClusterPropertiesAutoScalerProfile autoScalerProfile = null; + if (cluster.innerModel().autoScalerProfile() != null) { + autoScalerProfile = newSubresource(ClusterPropertiesAutoScalerProfile.class); + autoScalerProfile.copyFrom(cluster.innerModel().autoScalerProfile()); + } + setAutoScalerProfile(autoScalerProfile); + } + + @Override + public boolean refresh() { + AzureResourceManager client = createResourceManagerClient(); + KubernetesClusters kubernetesClusters = client.kubernetesClusters(); + KubernetesCluster cluster = kubernetesClusters.list().stream() + .filter(o -> o.name().equals(getName())) + .filter(o -> o.resourceGroupName().equals(getResourceGroup().getName())) + .findFirst().orElse(null); + + if (cluster != null) { + copyFrom(cluster); + + return true; + } + + return false; + } + + @Override + public void create(GyroUI ui, State state) throws Exception { + AzureResourceManager client = createResourceManagerClient(); + + WithServicePrincipalClientId withServicePrincipalClientId = client.kubernetesClusters() + .define(getName()) + .withRegion(Region.fromName(getRegion())) + .withExistingResourceGroup(getResourceGroup().getName()) + .withVersion(getVersion()) + .withRootUsername(getLinuxRootUsername()) + .withSshKey(getSshKey()); + + WithAgentPool withAgentPool = null; + WithCreate withCreate = null; + if (StringUtils.isBlank(getServicePrincipalClientId())) { + withCreate = withServicePrincipalClientId.withSystemAssignedManagedServiceIdentity(); + } else { + withAgentPool = withServicePrincipalClientId + .withServicePrincipalClientId(getServicePrincipalClientId()) + .withServicePrincipalSecret(getServicePrincipalSecret()); + } + + Blank createStage; + for (ClusterAgentPool agentPool : getAgentPool()) { + if (withCreate == null) { + createStage = withAgentPool.defineAgentPool(agentPool.getName()); + } else { + createStage = withCreate.defineAgentPool(agentPool.getName()); + } + + WithAttach withAttach = createStage + .withVirtualMachineSize(ContainerServiceVMSizeTypes.fromString(agentPool.getSize())) + .withAgentPoolVirtualMachineCount(agentPool.getCount()) + + .withTags(agentPool.getTags()) + .withAgentPoolMode(AgentPoolMode.fromString(agentPool.getMode())) + .withAgentPoolType(AgentPoolType.fromString(agentPool.getType())) + .withAvailabilityZones(agentPool.getAvailabilityZones().toArray(Integer[]::new)) + .withKubeletDiskType(KubeletDiskType.fromString(agentPool.getKubeletDiskType())) + .withNodeLabels(agentPool.getNodeLabels()) + .withNodeTaints(agentPool.getNodeTaints()) + .withOSType(OSType.fromString(agentPool.getOsType())) + .withOSDiskType(OSDiskType.fromString(agentPool.getOsDiskType())) + .withOSDiskSizeInGB(agentPool.getOsDiskSizeInGb()) + .withVirtualNetwork(agentPool.getNetwork().getId(), agentPool.getSubnet()) + .withMaxPodsCount(agentPool.getMaximumPodsPerNode()); + + if (agentPool.getAutoScalingEnabled()) { + withAttach = withAttach.withAutoScaling(agentPool.getMinimumNodeSize(), + agentPool.getMaximumNodeSize()); + } + + if (!StringUtils.isBlank(agentPool.getVirtualMachineEvictionPolicy())) { + withCreate = withAttach.withSpotPriorityVirtualMachine() + .withSpotPriorityVirtualMachine(ScaleSetEvictionPolicy.fromString(agentPool.getVirtualMachineEvictionPolicy())) + .withVirtualMachineMaximumPrice(agentPool.getVirtualMachineMaximumPrice()) + .withVirtualMachinePriority(ScaleSetPriority.fromString(agentPool.getVirtualMachinePriority())) + .attach(); + } else { + withCreate = withAttach.attach(); + } + } + + if (!getTags().isEmpty()) { + withCreate = withCreate.withTags(getTags()); + } + + if (getEnablePrivateCluster()) { + withCreate = withCreate.enablePrivateCluster(); + } + + if (!getAddonProfile().isEmpty()) { + withCreate = withCreate.withAddOnProfiles(getAddonProfile() + .stream() + .collect(Collectors.toMap(o -> o.getIdentity().getId(), + ClusterAddonProfile::toAddonProfile))); + } + + if (getAutoScalerProfile() != null) { + withCreate = withCreate.withAutoScalerProfile(getAutoScalerProfile().toAutoScalerProfile()); + } + + if (!StringUtils.isBlank(getDnsPrefix())) { + withCreate = withCreate.withDnsPrefix(getDnsPrefix()); + } + + KubernetesCluster cluster = withCreate.create(); + + setId(cluster.id()); + + KubernetesCluster.Update update = cluster.update(); + + if (getNetworkProfile() != null) { + NetworkProfile networkProfile = getNetworkProfile(); + setNetworkProfile(null); + state.save(); + setNetworkProfile(networkProfile); + update = update.withNetworkProfile(getNetworkProfile().toNetworkProfile()); + } + + if (getEnableRbac()) { + update = update.withRBACEnabled(); + } else { + update = update.withRBACDisabled(); + } + + update.apply(); + + copyFrom(cluster); + } + + @Override + public void update( + GyroUI ui, State state, Resource current, Set changedFieldNames) throws Exception { + + AzureResourceManager client = createResourceManagerClient(); + + KubernetesCluster cluster = client.kubernetesClusters() + .getByResourceGroup(getResourceGroup().getName(), getName()); + + KubernetesCluster.Update update = cluster.update(); + + + if (changedFieldNames.contains("enable-rbac")) { + if (getEnableRbac()) { + update = update.withRBACEnabled(); + } else { + update = update.withRBACDisabled(); + } + } + + if (changedFieldNames.contains("addon-profile")) { + update = update.withAddOnProfiles(getAddonProfile() + .stream() + .collect(Collectors.toMap(o -> o.getIdentity().getId(), + ClusterAddonProfile::toAddonProfile))); + } + + if (changedFieldNames.contains("network-profile")) { + update = update.withNetworkProfile(getNetworkProfile().toNetworkProfile()); + } + + if (changedFieldNames.contains("auto-scaler-profile")) { + update = update.withAutoScalerProfile(getAutoScalerProfile().toAutoScalerProfile()); + } + + if (changedFieldNames.contains("tags")) { + update = update.withTags(getTags()); + } + + if (changedFieldNames.contains("agent-pool")) { + KubernetesClusterResource currentClusterResource = (KubernetesClusterResource) current; + + Set currentAgentPool = currentClusterResource.getAgentPool(); + Set pendingAgentPool = getAgentPool(); + + Set currentAgentPoolNames = currentAgentPool.stream().map(ClusterAgentPool::getName).collect(Collectors.toSet()); + Set pendingAgentPoolNames = currentAgentPool.stream().map(ClusterAgentPool::getName).collect(Collectors.toSet()); + + List deleteAgentPool = currentAgentPoolNames.stream() + .filter(o -> !pendingAgentPoolNames.contains(o)) + .collect(Collectors.toList()); + + List modifyAgentPool = pendingAgentPool.stream() + .filter(o -> currentAgentPoolNames.contains(o.getName())) + .collect(Collectors.toList()); + + List addAgentPool = pendingAgentPool.stream() + .filter(o -> !currentAgentPoolNames.contains(o.getName())) + .collect(Collectors.toList()); + + if (!deleteAgentPool.isEmpty()) { + for (String poolName : deleteAgentPool) { + update = update.withoutAgentPool(poolName); + } + } + + if (!modifyAgentPool.isEmpty()) { + for (ClusterAgentPool agentPool : modifyAgentPool) { + update = update.updateAgentPool(agentPool.getName()) + .withAgentPoolVirtualMachineCount(agentPool.getCount()) + .withTags(agentPool.getTags()) + .withAgentPoolMode(AgentPoolMode.fromString(agentPool.getMode())) + .withAutoScaling(agentPool.getMinimumNodeSize(), agentPool.getMaximumNodeSize()) + .withKubeletDiskType(KubeletDiskType.fromString(agentPool.getKubeletDiskType())) + .parent(); + } + } + + if (!addAgentPool.isEmpty()) { + for (ClusterAgentPool agentPool : addAgentPool) { + WithAttach withAttach = update.defineAgentPool(agentPool.getName()) + .withVirtualMachineSize(ContainerServiceVMSizeTypes.fromString(agentPool.getSize())) + .withAgentPoolVirtualMachineCount(agentPool.getCount()) + + .withTags(agentPool.getTags()) + .withAgentPoolMode(AgentPoolMode.fromString(agentPool.getMode())) + .withAgentPoolType(AgentPoolType.fromString(agentPool.getType())) + .withAvailabilityZones(agentPool.getAvailabilityZones().toArray(Integer[]::new)) + .withKubeletDiskType(KubeletDiskType.fromString(agentPool.getKubeletDiskType())) + .withNodeLabels(agentPool.getNodeLabels()) + .withNodeTaints(agentPool.getNodeTaints()) + .withOSType(OSType.fromString(agentPool.getOsType())) + .withOSDiskType(OSDiskType.fromString(agentPool.getOsDiskType())) + .withOSDiskSizeInGB(agentPool.getOsDiskSizeInGb()) + .withVirtualNetwork(agentPool.getNetwork().getId(), agentPool.getSubnet()) + .withMaxPodsCount(agentPool.getMaximumPodsPerNode()); + + if (agentPool.getAutoScalingEnabled()) { + withAttach = withAttach.withAutoScaling(agentPool.getMinimumNodeSize(), + agentPool.getMaximumNodeSize()); + } + + if (!StringUtils.isBlank(agentPool.getVirtualMachineEvictionPolicy())) { + update = withAttach.withSpotPriorityVirtualMachine() + .withSpotPriorityVirtualMachine(ScaleSetEvictionPolicy.fromString(agentPool.getVirtualMachineEvictionPolicy())) + .withVirtualMachineMaximumPrice(agentPool.getVirtualMachineMaximumPrice()) + .withVirtualMachinePriority(ScaleSetPriority.fromString(agentPool.getVirtualMachinePriority())) + .attach(); + } else { + update = withAttach.attach(); + } + } + } + } + + update.apply(); + } + + @Override + public void delete(GyroUI ui, State state) throws Exception { + AzureResourceManager client = createResourceManagerClient(); + + client.kubernetesClusters().deleteByResourceGroup(getResourceGroup().getName(), getName()); + } +} diff --git a/src/main/java/gyro/azure/containerservice/NetworkProfile.java b/src/main/java/gyro/azure/containerservice/NetworkProfile.java new file mode 100644 index 00000000..03d9c7e8 --- /dev/null +++ b/src/main/java/gyro/azure/containerservice/NetworkProfile.java @@ -0,0 +1,252 @@ +package gyro.azure.containerservice; + +import com.azure.resourcemanager.containerservice.models.ContainerServiceNetworkProfile; +import com.azure.resourcemanager.containerservice.models.LoadBalancerSku; +import com.azure.resourcemanager.containerservice.models.NetworkMode; +import com.azure.resourcemanager.containerservice.models.NetworkPlugin; +import com.azure.resourcemanager.containerservice.models.NetworkPolicy; +import com.azure.resourcemanager.containerservice.models.OutboundType; +import gyro.azure.Copyable; +import gyro.core.resource.Diffable; +import gyro.core.resource.Updatable; +import gyro.core.validation.Required; +import gyro.core.validation.ValidStrings; +import org.apache.commons.lang3.StringUtils; + +public class NetworkProfile extends Diffable implements Copyable { + + private String dnsServiceIp; + private String dockerBridgeCidr; + private String networkPlugin; + private String networkMode; + private String networkPolicy; + private ClusterLoadBalancerProfile loadBalancerProfile; + private String loadBalancerSku; + private ClusterNatGatewayProfile natGatewayProfile; + private String outboundType; + private String podCidr; + private String serviceCidr; + + /** + * The dns service ip for the network profile. + */ + @Updatable + public String getDnsServiceIp() { + return dnsServiceIp; + } + + public void setDnsServiceIp(String dnsServiceIp) { + this.dnsServiceIp = dnsServiceIp; + } + + /** + * The docker bridge cidr for the network profile. + */ + @Updatable + public String getDockerBridgeCidr() { + return dockerBridgeCidr; + } + + public void setDockerBridgeCidr(String dockerBridgeCidr) { + this.dockerBridgeCidr = dockerBridgeCidr; + } + + /** + * The network plugin for the network profile. + */ + @Updatable + @ValidStrings({"azure", "kubenet"}) + public String getNetworkPlugin() { + return networkPlugin; + } + + public void setNetworkPlugin(String networkPlugin) { + this.networkPlugin = networkPlugin; + } + + /** + * The network mode for the network profile. + */ + @Updatable + @ValidStrings({"transparent", "bridge"}) + public String getNetworkMode() { + return networkMode; + } + + public void setNetworkMode(String networkMode) { + this.networkMode = networkMode; + } + + /** + * The network policy for the network profile. + */ + @Updatable + @ValidStrings({"calico", "azure"}) + public String getNetworkPolicy() { + return networkPolicy; + } + + public void setNetworkPolicy(String networkPolicy) { + this.networkPolicy = networkPolicy; + } + + /** + * The loadbalancer config for the network profile. + * + * @subresource gyro.azure.containerservice.ClusterLoadBalancerProfile + */ + @Updatable + public ClusterLoadBalancerProfile getLoadBalancerProfile() { + return loadBalancerProfile; + } + + public void setLoadBalancerProfile(ClusterLoadBalancerProfile loadBalancerProfile) { + this.loadBalancerProfile = loadBalancerProfile; + } + + /** + * The load balancer sku for the network profile. + */ + @Updatable + @ValidStrings({"standard", "basic"}) + public String getLoadBalancerSku() { + return loadBalancerSku; + } + + public void setLoadBalancerSku(String loadBalancerSku) { + this.loadBalancerSku = loadBalancerSku; + } + + /** + * The natgateway config for the network profile. + * + * @subresource gyro.azure.containerservice.ClusterNatGatewayProfile + */ + @Updatable + public ClusterNatGatewayProfile getNatGatewayProfile() { + return natGatewayProfile; + } + + public void setNatGatewayProfile(ClusterNatGatewayProfile natGatewayProfile) { + this.natGatewayProfile = natGatewayProfile; + } + + /** + * The outbound type for the network profile. + */ + @Updatable + @ValidStrings({"loadBalancer", "userDefinedRouting", "managedNATGateway", "userAssignedNATGateway"}) + public String getOutboundType() { + return outboundType; + } + + public void setOutboundType(String outboundType) { + this.outboundType = outboundType; + } + + /** + * The pod cidr for the network profile. + */ + @Updatable + public String getPodCidr() { + return podCidr; + } + + public void setPodCidr(String podCidr) { + this.podCidr = podCidr; + } + + /** + * The service cidr for the network profile. + */ + @Updatable + public String getServiceCidr() { + return serviceCidr; + } + + public void setServiceCidr(String serviceCidr) { + this.serviceCidr = serviceCidr; + } + + @Override + public void copyFrom(ContainerServiceNetworkProfile model) { + setDnsServiceIp(model.dnsServiceIp()); + setDockerBridgeCidr(model.dockerBridgeCidr()); + setNetworkPlugin(model.networkPlugin().toString()); + setNetworkMode(model.networkMode() != null ? model.networkMode().toString() : null); + setNetworkPolicy(model.networkPolicy() != null ? model.networkPolicy().toString() : null); + setLoadBalancerSku(model.loadBalancerSku() != null ? model.loadBalancerSku().toString() : null); + setOutboundType(model.outboundType() != null ? model.outboundType().toString() : null); + setPodCidr(model.podCidr()); + setServiceCidr(model.serviceCidr()); + + ClusterNatGatewayProfile clusterNatGatewayProfile = null; + if (model.natGatewayProfile() != null) { + clusterNatGatewayProfile = newSubresource(ClusterNatGatewayProfile.class); + clusterNatGatewayProfile.copyFrom(model.natGatewayProfile()); + } + setNatGatewayProfile(clusterNatGatewayProfile); + + ClusterLoadBalancerProfile clusterLoadBalancerProfile = null; + if (model.loadBalancerProfile() != null) { + clusterLoadBalancerProfile = newSubresource(ClusterLoadBalancerProfile.class); + clusterLoadBalancerProfile.copyFrom(model.loadBalancerProfile()); + } + setLoadBalancerProfile(clusterLoadBalancerProfile); + } + + @Override + public String primaryKey() { + return ""; + } + + protected ContainerServiceNetworkProfile toNetworkProfile() { + ContainerServiceNetworkProfile networkProfile = new ContainerServiceNetworkProfile(); + + if (!StringUtils.isBlank(getNetworkPlugin())) { + networkProfile.withNetworkPlugin(NetworkPlugin.fromString(getNetworkPlugin())); + } + + if (!StringUtils.isBlank(getNetworkPolicy())) { + networkProfile.withNetworkPolicy(NetworkPolicy.fromString(getNetworkPolicy())); + } + + if (!StringUtils.isBlank(getNetworkMode())) { + networkProfile.withNetworkMode(NetworkMode.fromString(getNetworkMode())); + } + + if (!StringUtils.isBlank(getDnsServiceIp())) { + networkProfile.withDnsServiceIp(getDnsServiceIp()); + } + + if (!StringUtils.isBlank(getPodCidr())) { + networkProfile.withPodCidr(getPodCidr()); + } + + if (!StringUtils.isBlank(getOutboundType())) { + networkProfile.withOutboundType(OutboundType.fromString(getOutboundType())); + } + + if (!StringUtils.isBlank(getDockerBridgeCidr())) { + networkProfile.withDockerBridgeCidr(getDockerBridgeCidr()); + } + + if (!StringUtils.isBlank(getServiceCidr())) { + networkProfile.withServiceCidr(getServiceCidr()); + } + + if (!StringUtils.isBlank(getLoadBalancerSku())) { + networkProfile.withLoadBalancerSku(LoadBalancerSku.fromString(getLoadBalancerSku())); + } + + if (getLoadBalancerProfile() != null) { + networkProfile.withLoadBalancerProfile(getLoadBalancerProfile().toClusterLoadBalancerProfile()); + } + + if (getNatGatewayProfile() != null) { + networkProfile.withNatGatewayProfile(getNatGatewayProfile().toNatGatewayProfile()); + } + + return networkProfile; + } +} From 9b8bc074fb675678e418dc3ff5aa46a14c9c2f4a Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Thu, 17 Feb 2022 17:37:01 -0500 Subject: [PATCH 08/43] initial storage refactor The storage package refactor is limited with a bunch of non refactored resources Mostly Storage Account and blob container is refactored. Storage account still needs to refactoring to enable cors and lifecycle rules. Filebackend will require changes as well --- examples/storage/cloud-blob-container.gyro | 11 +- .../azure/CloudBlobContainerFileBackend.java | 2 +- .../storage/CloudBlobContainerResource.java | 126 +++++++++------- .../azure/storage/StorageAccountFinder.java | 15 +- .../azure/storage/StorageAccountResource.java | 139 +++--------------- 5 files changed, 101 insertions(+), 192 deletions(-) diff --git a/examples/storage/cloud-blob-container.gyro b/examples/storage/cloud-blob-container.gyro index 1aec2e20..0b93b46e 100644 --- a/examples/storage/cloud-blob-container.gyro +++ b/examples/storage/cloud-blob-container.gyro @@ -10,15 +10,6 @@ azure::storage-account blob-storage-account-example resource-group: $(azure::resource-group blob-resource-group) name: "testblobexample" - cors-rule - allowed-headers: ["*"] - allowed-methods: ["POST"] - allowed-origins: ["*"] - exposed-headers: ["*"] - max-age: 6 - type: "blob" - end - tags: { Name: "testblobexample" } @@ -26,6 +17,6 @@ end azure::cloud-blob-container blob-container-example name: "blobcontainerexample" - public-access: "CONTAINER" + public-access: "Container" storage-account: $(azure::storage-account blob-storage-account-example) end diff --git a/src/main/java/gyro/azure/CloudBlobContainerFileBackend.java b/src/main/java/gyro/azure/CloudBlobContainerFileBackend.java index 98ea2e16..fd853dec 100644 --- a/src/main/java/gyro/azure/CloudBlobContainerFileBackend.java +++ b/src/main/java/gyro/azure/CloudBlobContainerFileBackend.java @@ -147,7 +147,7 @@ private CloudBlobContainer container() { .map(e -> e.getByResourceGroup(getResourceGroup(), account)) .orElseThrow(() -> new GyroException("No storage account available!")); StorageAccountResource storage = getRootScope().findResourceById(StorageAccountResource.class, account); - storage.copyFrom(storageAccount); + // storage.copyFrom(storageAccount); // TODO handle this try { CloudStorageAccount cloudStorageAccount = CloudStorageAccount.parse(storage.getConnection()); diff --git a/src/main/java/gyro/azure/storage/CloudBlobContainerResource.java b/src/main/java/gyro/azure/storage/CloudBlobContainerResource.java index 7b472a37..847025da 100644 --- a/src/main/java/gyro/azure/storage/CloudBlobContainerResource.java +++ b/src/main/java/gyro/azure/storage/CloudBlobContainerResource.java @@ -16,9 +16,11 @@ package gyro.azure.storage; +import com.azure.resourcemanager.storage.models.BlobContainer; +import com.azure.resourcemanager.storage.models.PublicAccess; +import com.azure.resourcemanager.storage.models.StorageAccount; import gyro.azure.AzureResource; import gyro.azure.Copyable; -import gyro.core.GyroException; import gyro.core.GyroUI; import gyro.core.resource.Id; import gyro.core.resource.Output; @@ -26,18 +28,12 @@ import gyro.core.Type; import gyro.core.resource.Resource; -import com.microsoft.azure.storage.blob.BlobContainerPermissions; -import com.microsoft.azure.storage.CloudStorageAccount; -import com.microsoft.azure.storage.StorageException; -import com.microsoft.azure.storage.blob.BlobContainerPublicAccessType; -import com.microsoft.azure.storage.blob.CloudBlobClient; -import com.microsoft.azure.storage.blob.CloudBlobContainer; import gyro.core.scope.State; import gyro.core.validation.Required; import gyro.core.validation.ValidStrings; -import java.net.URISyntaxException; -import java.security.InvalidKeyException; +import java.util.HashMap; +import java.util.Map; import java.util.Set; /** @@ -55,12 +51,13 @@ * end */ @Type("cloud-blob-container") -public class CloudBlobContainerResource extends AzureResource implements Copyable { +public class CloudBlobContainerResource extends AzureResource implements Copyable { private String name; private String publicAccess; private StorageAccountResource storageAccount; private String id; + private Map metadata; /** * The name of the container. @@ -76,10 +73,10 @@ public void setName(String name) { } /** - * The public access of the container. Valid values are ``BLOB`` or ``CONTAINER`` or ``OFF`` + * The public access of the container. Valid values are ``Blob`` or ``Container`` or ``Off`` */ @Required - @ValidStrings({"BLOB", "CONTAINER", "OFF"}) + @ValidStrings({"Blob", "Container", "Off"}) @Updatable public String getPublicAccess() { return publicAccess; @@ -101,6 +98,18 @@ public void setStorageAccount(StorageAccountResource storageAccount) { this.storageAccount = storageAccount; } + public Map getMetadata() { + if (metadata == null) { + metadata = new HashMap<>(); + } + + return metadata; + } + + public void setMetadata(Map metadata) { + this.metadata = metadata; + } + /** * The ID of the blob container. */ @@ -114,72 +123,77 @@ public void setId(String id) { } @Override - public void copyFrom(CloudBlobContainer container) { - setStorageAccount(findById(StorageAccountResource.class, container.getStorageUri().getPrimaryUri().getAuthority().split(".blob.core")[0])); - setPublicAccess(container.getProperties().getPublicAccess().toString()); - setName(container.getName()); - setId(String.format("%s/blobServices/default/containers/%s",getStorageAccount().getId(),getName())); + public void copyFrom(BlobContainer container) { + setPublicAccess(container.publicAccess().toString()); + setName(container.name()); + setId(container.id()); + setMetadata(container.metadata()); + + String storageAccountName = getId() + .split("Microsoft.Storage/storageAccounts/")[1] + .split("/blobServices")[0]; + setStorageAccount(findById(StorageAccountResource.class, storageAccountName)); } @Override public boolean refresh() { - try { - CloudBlobContainer container = cloudBlobContainer(); - if (!container.exists()) { - return false; - } + StorageAccount storageAccount = getStorageAccount().getStorageAccount(); - copyFrom(container); + BlobContainer blobContainer = storageAccount.manager().blobContainers() + .get(storageAccount.resourceGroupName(), storageAccount.name(), getName()); - return true; - } catch (StorageException ex) { + if (blobContainer == null) { return false; } + + copyFrom(blobContainer); + + return true; } @Override public void create(GyroUI ui, State state) { - try { - CloudBlobContainer container = cloudBlobContainer(); - container.create(); - BlobContainerPermissions permissions = new BlobContainerPermissions(); - permissions.setPublicAccess(BlobContainerPublicAccessType.valueOf(getPublicAccess())); - container.uploadPermissions(permissions); - setId(String.format("%s/blobServices/default/containers/%s",getStorageAccount().getId(),getName())); - } catch (StorageException ex) { - throw new GyroException(ex.getMessage()); + StorageAccount storageAccount = getStorageAccount().getStorageAccount(); + + BlobContainer.DefinitionStages.WithCreate withCreate = storageAccount.manager().blobContainers() + .defineContainer(getName()) + .withExistingStorageAccount(storageAccount) + .withPublicAccess(PublicAccess.fromString(getPublicAccess())); + + if (!getMetadata().isEmpty()) { + withCreate.withMetadata(getMetadata()); } + + BlobContainer blobContainer = withCreate.create(); + + copyFrom(blobContainer); } @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) { - try { - CloudBlobContainer container = cloudBlobContainer(); - BlobContainerPermissions permissions = new BlobContainerPermissions(); - permissions.setPublicAccess(BlobContainerPublicAccessType.valueOf(getPublicAccess())); - container.uploadPermissions(permissions); - } catch (StorageException ex) { - throw new GyroException(ex.getMessage()); + StorageAccount storageAccount = getStorageAccount().getStorageAccount(); + + BlobContainer blobContainer = storageAccount.manager().blobContainers() + .get(storageAccount.resourceGroupName(), storageAccount.name(), getName()); + + BlobContainer.Update update = blobContainer.update(); + + if (changedFieldNames.contains("metadata")) { + update = update.withMetadata(getMetadata()); + } + + if (changedFieldNames.contains("public-access")) { + update = update.withPublicAccess(PublicAccess.fromString(getPublicAccess())); } + + update.apply(); } @Override public void delete(GyroUI ui, State state) { - try { - CloudBlobContainer container = cloudBlobContainer(); - container.delete(); - } catch (StorageException ex) { - throw new GyroException(ex.getMessage()); - } - } + StorageAccount storageAccount = getStorageAccount().getStorageAccount(); - private CloudBlobContainer cloudBlobContainer() { - try { - CloudStorageAccount account = CloudStorageAccount.parse(getStorageAccount().getConnection()); - CloudBlobClient blobClient = account.createCloudBlobClient(); - return blobClient.getContainerReference(getName()); - } catch (StorageException | URISyntaxException | InvalidKeyException ex) { - throw new GyroException(ex.getMessage()); - } + storageAccount.manager().blobContainers() + .delete(storageAccount.resourceGroupName(), storageAccount.name(), getName()); } } diff --git a/src/main/java/gyro/azure/storage/StorageAccountFinder.java b/src/main/java/gyro/azure/storage/StorageAccountFinder.java index 8be78205..b99b7d8c 100644 --- a/src/main/java/gyro/azure/storage/StorageAccountFinder.java +++ b/src/main/java/gyro/azure/storage/StorageAccountFinder.java @@ -16,17 +16,18 @@ package gyro.azure.storage; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.storage.StorageAccount; -import gyro.azure.AzureFinder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.storage.models.StorageAccount; +import gyro.azure.AzureResourceManagerFinder; import gyro.core.Type; import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; @Type("storage-account") -public class StorageAccountFinder extends AzureFinder { +public class StorageAccountFinder extends AzureResourceManagerFinder { private String id; /** @@ -41,12 +42,12 @@ public void setId(String id) { } @Override - protected List findAllAzure(Azure client) { - return client.storageAccounts().list(); + protected List findAllAzure(AzureResourceManager client) { + return client.storageAccounts().list().stream().collect(Collectors.toList()); } @Override - protected List findAzure(Azure client, Map filters) { + protected List findAzure(AzureResourceManager client, Map filters) { StorageAccount storageAccount = client.storageAccounts().getById(filters.get("id")); if (storageAccount == null) { return Collections.emptyList(); diff --git a/src/main/java/gyro/azure/storage/StorageAccountResource.java b/src/main/java/gyro/azure/storage/StorageAccountResource.java index 9e9d098e..5dd257e2 100644 --- a/src/main/java/gyro/azure/storage/StorageAccountResource.java +++ b/src/main/java/gyro/azure/storage/StorageAccountResource.java @@ -16,15 +16,10 @@ package gyro.azure.storage; -import com.microsoft.azure.management.storage.Kind; -import com.microsoft.azure.storage.CloudStorageAccount; -import com.microsoft.azure.storage.ServiceProperties; -import com.microsoft.azure.storage.StorageException; -import com.microsoft.azure.storage.blob.CloudBlobClient; -import com.microsoft.azure.storage.file.CloudFileClient; -import com.microsoft.azure.storage.file.FileServiceProperties; -import com.microsoft.azure.storage.queue.CloudQueueClient; -import com.microsoft.azure.storage.table.CloudTableClient; +import com.azure.core.management.Region; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.storage.models.Kind; +import com.azure.resourcemanager.storage.models.StorageAccount; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.azure.resources.ResourceGroupResource; @@ -35,11 +30,6 @@ import gyro.core.Type; import gyro.core.resource.Output; import gyro.core.resource.Resource; - -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.resources.fluentcore.arm.Region; -import com.microsoft.azure.management.storage.StorageAccount; -import com.microsoft.azure.management.storage.StorageAccountKey; import gyro.core.scope.State; import gyro.core.validation.Required; @@ -47,7 +37,6 @@ import java.security.InvalidKeyException; import java.util.HashMap; import java.util.HashSet; -import java.util.List; import java.util.Map; import java.util.Set; @@ -216,52 +205,8 @@ public void setUpgradeAccountV2(Boolean upgradeAccountV2) { @Override public void copyFrom(StorageAccount storageAccount) { - try { - setId(storageAccount.id()); - setName(storageAccount.name()); - - CloudStorageAccount cloudStorageAccount = CloudStorageAccount.parse(getConnection()); - - getCorsRule().clear(); - CloudBlobClient blobClient = cloudStorageAccount.createCloudBlobClient(); - blobClient.downloadServiceProperties().getCors() - .getCorsRules().forEach(cors -> { - Cors rule = newSubresource(Cors.class); - rule.copyFrom(cors); - rule.setType("blob"); - getCorsRule().add(rule); - }); - - CloudFileClient fileClient = cloudStorageAccount.createCloudFileClient(); - fileClient.downloadServiceProperties().getCors() - .getCorsRules().forEach(cors -> { - Cors rule = newSubresource(Cors.class); - rule.copyFrom(cors); - rule.setType("file"); - getCorsRule().add(rule); - }); - - CloudQueueClient queueClient = cloudStorageAccount.createCloudQueueClient(); - queueClient.downloadServiceProperties().getCors() - .getCorsRules().forEach(cors -> { - Cors rule = newSubresource(Cors.class); - rule.copyFrom(cors); - rule.setType("queue"); - getCorsRule().add(rule); - }); - - CloudTableClient tableClient = cloudStorageAccount.createCloudTableClient(); - tableClient.downloadServiceProperties().getCors() - .getCorsRules().forEach(cors -> { - Cors rule = newSubresource(Cors.class); - rule.copyFrom(cors); - rule.setType("table"); - getCorsRule().add(rule); - }); - - } catch (StorageException | URISyntaxException | InvalidKeyException ex) { - throw new GyroException(ex.getMessage()); - } + setId(storageAccount.id()); + setName(storageAccount.name()); setResourceGroup(findById(ResourceGroupResource.class, storageAccount.resourceGroupName())); setId(storageAccount.id()); @@ -269,26 +214,13 @@ public void copyFrom(StorageAccount storageAccount) { getTags().clear(); storageAccount.tags().forEach((key, value) -> getTags().put(key, value)); - - StorageLifeCycle lifeCycleManager = null; - if (storageAccount.manager().managementPolicies().inner().get(getResourceGroup().getName(), getName()) != null) { - lifeCycleManager = newSubresource(StorageLifeCycle.class); - lifeCycleManager.copyFrom( - storageAccount.manager() - .managementPolicies() - .getAsync(getResourceGroup().getName(), getName()) - .toBlocking() - .single() - ); - } - setLifecycle(lifeCycleManager); } @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); - StorageAccount storageAccount = client.storageAccounts().getById(getId()); + StorageAccount storageAccount = client.storageAccounts().getByResourceGroup(getResourceGroup().getName(), getName()); if (storageAccount == null) { return false; @@ -300,8 +232,8 @@ public boolean refresh() { } @Override - public void create(GyroUI ui, State state) throws StorageException, URISyntaxException, InvalidKeyException { - Azure client = createClient(); + public void create(GyroUI ui, State state) throws URISyntaxException, InvalidKeyException { + AzureResourceManager client = createResourceManagerClient(); StorageAccount.DefinitionStages.WithCreate withCreate = client.storageAccounts() .define(getName()) @@ -317,12 +249,12 @@ public void create(GyroUI ui, State state) throws StorageException, URISyntaxExc setId(storageAccount.id()); - updateCorsRules(); + // TODO lifecycle and cors } @Override - public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) throws StorageException, URISyntaxException, InvalidKeyException { - Azure client = createClient(); + public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) throws URISyntaxException, InvalidKeyException { + AzureResourceManager client = createResourceManagerClient(); StorageAccount storageAccount = client.storageAccounts().getById(getId()); StorageAccount.Update update = storageAccount.update(); @@ -338,50 +270,15 @@ public void update(GyroUI ui, State state, Resource current, Set changed } update.apply(); - - updateCorsRules(); } @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); client.storageAccounts().deleteById(getId()); } - private void updateCorsRules() throws StorageException, URISyntaxException, InvalidKeyException { - CloudStorageAccount cloudStorageAccount = CloudStorageAccount.parse(getConnection()); - - CloudBlobClient blobClient = cloudStorageAccount.createCloudBlobClient(); - ServiceProperties blobProperties = new ServiceProperties(); - - CloudFileClient fileClient = cloudStorageAccount.createCloudFileClient(); - FileServiceProperties fileProperties = new FileServiceProperties(); - - CloudQueueClient queueClient = cloudStorageAccount.createCloudQueueClient(); - ServiceProperties queueProperties = new ServiceProperties(); - - CloudTableClient tableClient = cloudStorageAccount.createCloudTableClient(); - ServiceProperties tableProperties = new ServiceProperties(); - - for (Cors rule : getCorsRule()) { - if (rule.getType().equalsIgnoreCase("blob")) { - blobProperties.getCors().getCorsRules().add(rule.toCors()); - } else if (rule.getType().equalsIgnoreCase("file")) { - fileProperties.getCors().getCorsRules().add(rule.toCors()); - } else if (rule.getType().equalsIgnoreCase("queue")) { - queueProperties.getCors().getCorsRules().add(rule.toCors()); - } else if (rule.getType().equalsIgnoreCase("table")) { - tableProperties.getCors().getCorsRules().add(rule.toCors()); - } - } - - blobClient.uploadServiceProperties(blobProperties); - fileClient.uploadServiceProperties(fileProperties); - queueClient.uploadServiceProperties(queueProperties); - tableClient.uploadServiceProperties(tableProperties); - } - public String getConnection() { return "DefaultEndpointsProtocol=https;" + "AccountName=" + getName() + ";" @@ -392,7 +289,7 @@ public Map keys() { Map keys = new HashMap<>(); if (getId() != null) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); StorageAccount storageAccount = client.storageAccounts().getById(getId()); storageAccount.getKeys().forEach(e -> keys.put(e.keyName(), e.value())); @@ -400,4 +297,10 @@ public Map keys() { return keys; } + + protected StorageAccount getStorageAccount() { + AzureResourceManager client = createResourceManagerClient(); + + return client.storageAccounts().getById(getId()); + } } From f1be6af4252fbcf57ce9bc756081f71df8b537a2 Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Thu, 17 Feb 2022 17:40:25 -0500 Subject: [PATCH 09/43] initial key vault refactor Mostly key vault, key and secret has been refactored. More work needs to be done to refactor the commands associated with creating these values. Certificates has not been touched --- examples/keyvault/key.gyro | 6 +- examples/keyvault/secret.gyro | 4 +- .../azure/keyvault/KeyVaultAccessPolicy.java | 16 ++-- .../keyvault/KeyVaultCertificateResource.java | 6 +- .../gyro/azure/keyvault/KeyVaultFinder.java | 31 ++++--- .../azure/keyvault/KeyVaultKeyAttribute.java | 29 +++--- .../azure/keyvault/KeyVaultKeyResource.java | 88 +++++++++++-------- .../gyro/azure/keyvault/KeyVaultResource.java | 38 ++++---- .../keyvault/KeyVaultSecretAttribute.java | 29 +++--- .../keyvault/KeyVaultSecretResource.java | 76 ++++++++-------- 10 files changed, 171 insertions(+), 152 deletions(-) diff --git a/examples/keyvault/key.gyro b/examples/keyvault/key.gyro index c0961e7c..c3f9bcea 100644 --- a/examples/keyvault/key.gyro +++ b/examples/keyvault/key.gyro @@ -42,11 +42,11 @@ azure::key-vault-key vault-key-example attribute enabled : false - expires : "2020-04-04T15:54:12.000Z" - not-before : "2020-04-02T15:54:12.000Z" + expires : "2020-04-04T15:54:12Z" + not-before : "2020-04-02T15:54:12Z" end tags: { Name: "vault-key-examples" } -end \ No newline at end of file +end diff --git a/examples/keyvault/secret.gyro b/examples/keyvault/secret.gyro index dd8a0e30..53effdd8 100644 --- a/examples/keyvault/secret.gyro +++ b/examples/keyvault/secret.gyro @@ -40,8 +40,8 @@ azure::key-vault-secret vault-secret-example attribute enabled : true - expires : "2020-04-04T15:54:12.000Z" - not-before : "2020-04-02T15:54:12.000Z" + expires : "2020-04-04T15:54:12Z" + not-before : "2020-04-02T15:54:12Z" end tags: { diff --git a/src/main/java/gyro/azure/keyvault/KeyVaultAccessPolicy.java b/src/main/java/gyro/azure/keyvault/KeyVaultAccessPolicy.java index 45624dbf..6ac2e8f2 100644 --- a/src/main/java/gyro/azure/keyvault/KeyVaultAccessPolicy.java +++ b/src/main/java/gyro/azure/keyvault/KeyVaultAccessPolicy.java @@ -20,14 +20,14 @@ import java.util.Set; import java.util.stream.Collectors; -import com.microsoft.azure.management.keyvault.AccessPolicy; -import com.microsoft.azure.management.keyvault.CertificatePermissions; -import com.microsoft.azure.management.keyvault.KeyPermissions; -import com.microsoft.azure.management.keyvault.Permissions; -import com.microsoft.azure.management.keyvault.SecretPermissions; -import com.microsoft.azure.management.keyvault.StoragePermissions; -import com.microsoft.azure.management.keyvault.Vault; -import com.microsoft.rest.ExpandableStringEnum; +import com.azure.core.util.ExpandableStringEnum; +import com.azure.resourcemanager.keyvault.models.AccessPolicy; +import com.azure.resourcemanager.keyvault.models.CertificatePermissions; +import com.azure.resourcemanager.keyvault.models.KeyPermissions; +import com.azure.resourcemanager.keyvault.models.Permissions; +import com.azure.resourcemanager.keyvault.models.SecretPermissions; +import com.azure.resourcemanager.keyvault.models.StoragePermissions; +import com.azure.resourcemanager.keyvault.models.Vault; import gyro.azure.Copyable; import gyro.core.resource.Diffable; import gyro.core.resource.Output; diff --git a/src/main/java/gyro/azure/keyvault/KeyVaultCertificateResource.java b/src/main/java/gyro/azure/keyvault/KeyVaultCertificateResource.java index 417f6a56..1189f74c 100644 --- a/src/main/java/gyro/azure/keyvault/KeyVaultCertificateResource.java +++ b/src/main/java/gyro/azure/keyvault/KeyVaultCertificateResource.java @@ -255,7 +255,7 @@ public void copyFrom(CertificateBundle certificateBundle) { @Override public boolean refresh() { - Vault vault = getVault().getKeyVault(); + Vault vault = getVault().getOldKeyVault(); CertificateBundle certificateBundle = vault.client().getCertificate(vault.vaultUri(), getName()); return certificateBundle != null; @@ -263,7 +263,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) throws Exception { - Vault vault = getVault().getKeyVault(); + Vault vault = getVault().getOldKeyVault(); CreateCertificateRequest.Builder builder = new CreateCertificateRequest.Builder(vault.vaultUri(), getName()); builder = builder.withPolicy(getPolicy().toCertificatePolicy()); @@ -309,7 +309,7 @@ public void update( @Override public void delete(GyroUI ui, State state) throws Exception { - Vault vault = getVault().getKeyVault(); + Vault vault = getVault().getOldKeyVault(); vault.client().deleteCertificate(vault.id(), getName()); } } diff --git a/src/main/java/gyro/azure/keyvault/KeyVaultFinder.java b/src/main/java/gyro/azure/keyvault/KeyVaultFinder.java index 3c5d5640..3d9bae46 100644 --- a/src/main/java/gyro/azure/keyvault/KeyVaultFinder.java +++ b/src/main/java/gyro/azure/keyvault/KeyVaultFinder.java @@ -21,11 +21,10 @@ import java.util.Map; import java.util.stream.Collectors; -import com.microsoft.azure.PagedList; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.keyvault.Vault; -import com.microsoft.azure.management.resources.fluentcore.arm.models.HasName; -import gyro.azure.AzureFinder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.keyvault.models.Vault; +import com.azure.resourcemanager.resources.fluentcore.arm.models.HasName; +import gyro.azure.AzureResourceManagerFinder; import gyro.core.Type; /** @@ -39,7 +38,7 @@ * identity: $(external-query azure::key-vault {resource-group: "resource-group-example", name: "vault-example"}) */ @Type("key-vault") -public class KeyVaultFinder extends AzureFinder { +public class KeyVaultFinder extends AzureResourceManagerFinder { private String resourceGroup; private String name; @@ -67,34 +66,34 @@ public void setName(String name) { } @Override - protected List findAllAzure(Azure client) { + protected List findAllAzure(AzureResourceManager client) { List vaults = new ArrayList<>(); List resourceGroups = client.resourceGroups().list().stream().map(HasName::name).collect(Collectors.toList()); resourceGroups.forEach(o -> { - PagedList vaultPagedList = client.vaults().listByResourceGroup(o); - vaultPagedList.loadAll(); - vaults.addAll(vaultPagedList); + List vaultList = client.vaults() + .listByResourceGroup(o).stream().collect(Collectors.toList()); + vaults.addAll(vaultList); }); return vaults; } @Override - protected List findAzure(Azure client, Map filters) { + protected List findAzure(AzureResourceManager client, Map filters) { List vaults = new ArrayList<>(); if (filters.containsKey("resource-group")) { if (filters.containsKey("name")) { - Vault vault = client.vaults().getByResourceGroup(filters.get("resource-group"), filters.get("name")); + Vault vault = client.vaults() + .getByResourceGroup(filters.get("resource-group"), filters.get("name")); if (vault != null) { vaults.add(vault); } } else { - PagedList vaultPagedList = client.vaults().listByResourceGroup(filters.get("resource-group")); - if (vaultPagedList != null) { - vaultPagedList.loadAll(); - vaults.addAll(vaultPagedList); + List vaultList = client.vaults().listByResourceGroup(filters.get("resource-group")).stream().collect(Collectors.toList()); + if (!vaultList.isEmpty()) { + vaults.addAll(vaultList); } } } diff --git a/src/main/java/gyro/azure/keyvault/KeyVaultKeyAttribute.java b/src/main/java/gyro/azure/keyvault/KeyVaultKeyAttribute.java index 49095b35..dd4d5bd4 100644 --- a/src/main/java/gyro/azure/keyvault/KeyVaultKeyAttribute.java +++ b/src/main/java/gyro/azure/keyvault/KeyVaultKeyAttribute.java @@ -1,14 +1,15 @@ package gyro.azure.keyvault; -import com.microsoft.azure.keyvault.models.KeyAttributes; +import java.time.OffsetDateTime; + +import com.azure.security.keyvault.keys.models.KeyProperties; import gyro.azure.Copyable; import gyro.core.resource.Diffable; import gyro.core.resource.Output; import gyro.core.resource.Updatable; import gyro.core.validation.Required; -import org.joda.time.DateTime; -public class KeyVaultKeyAttribute extends Diffable implements Copyable { +public class KeyVaultKeyAttribute extends Diffable implements Copyable { private Boolean enabled; private String expires; @@ -83,18 +84,18 @@ public String primaryKey() { } @Override - public void copyFrom(KeyAttributes attributes) { - setEnabled(attributes.enabled()); - setExpires(attributes.expires() != null ? attributes.expires().toString() : null); - setNotBefore(attributes.notBefore() != null ? attributes.notBefore().toString() : null); - setCreated(attributes.created() != null ? attributes.created().toString() : null); - setUpdated(attributes.updated() != null ? attributes.updated().toString() : null); + public void copyFrom(KeyProperties properties) { + setEnabled(properties.isEnabled()); + setExpires(properties.getExpiresOn() != null ? properties.getExpiresOn().toString() : null); + setNotBefore(properties.getNotBefore() != null ? properties.getNotBefore().toString() : null); + setCreated(properties.getCreatedOn() != null ? properties.getCreatedOn().toString() : null); + setUpdated(properties.getUpdatedOn() != null ? properties.getUpdatedOn().toString() : null); } - KeyAttributes toKeyAttributes() { - return (KeyAttributes) new KeyAttributes() - .withEnabled(getEnabled()) - .withExpires(getExpires() != null ? DateTime.parse(getExpires()) : null) - .withNotBefore(getNotBefore() != null ? DateTime.parse(getNotBefore()) : null); + KeyProperties toKeyProperties() { + return new KeyProperties() + .setEnabled(getEnabled()) + .setExpiresOn(getExpires() != null ? OffsetDateTime.parse(getExpires()) : null) + .setNotBefore(getNotBefore() != null ? OffsetDateTime.parse(getNotBefore()) : null); } } diff --git a/src/main/java/gyro/azure/keyvault/KeyVaultKeyResource.java b/src/main/java/gyro/azure/keyvault/KeyVaultKeyResource.java index 11096a02..4a393fc5 100644 --- a/src/main/java/gyro/azure/keyvault/KeyVaultKeyResource.java +++ b/src/main/java/gyro/azure/keyvault/KeyVaultKeyResource.java @@ -7,13 +7,11 @@ import java.util.Set; import java.util.stream.Collectors; -import com.microsoft.azure.keyvault.KeyIdentifier; -import com.microsoft.azure.keyvault.models.KeyBundle; -import com.microsoft.azure.keyvault.requests.CreateKeyRequest; -import com.microsoft.azure.keyvault.requests.UpdateKeyRequest; -import com.microsoft.azure.keyvault.webkey.JsonWebKeyOperation; -import com.microsoft.azure.keyvault.webkey.JsonWebKeyType; -import com.microsoft.azure.management.keyvault.Vault; +import com.azure.core.util.ExpandableStringEnum; +import com.azure.resourcemanager.keyvault.models.Key; +import com.azure.resourcemanager.keyvault.models.Vault; +import com.azure.security.keyvault.keys.models.KeyOperation; +import com.azure.security.keyvault.keys.models.KeyType; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.core.GyroUI; @@ -53,7 +51,7 @@ * end */ @Type("key-vault-key") -public class KeyVaultKeyResource extends AzureResource implements Copyable { +public class KeyVaultKeyResource extends AzureResource implements Copyable { private String name; private KeyVaultResource vault; @@ -187,36 +185,33 @@ public void setTags(Map tags) { } @Override - public void copyFrom(KeyBundle key) { + public void copyFrom(Key key) { setTags(key.tags()); - setType(key.key().kty().toString()); - setOperations(key.key().keyOps().stream().map(JsonWebKeyOperation::toString).collect(Collectors.toList())); + setOperations(key.getJsonWebKey().getKeyOps().stream().map(ExpandableStringEnum::toString).collect(Collectors.toList())); KeyVaultKeyAttribute attribute = newSubresource(KeyVaultKeyAttribute.class); attribute.copyFrom(key.attributes()); setAttribute(attribute); - KeyIdentifier keyIdentifier = key.keyIdentifier(); - setId(keyIdentifier.identifier()); - setName(keyIdentifier.name()); - setVersion(keyIdentifier.version()); - - String vaultUri = keyIdentifier.vault(); - vaultUri = vaultUri.endsWith("/") ? vaultUri : vaultUri + "/"; - setVault(findById(KeyVaultResource.class, vaultUri)); + setId(key.id()); + setName(key.name()); + setVersion(key.innerModel().getVersion()); + String vaultName = getId().split(".vault.azure.net")[0].split("://")[1]; + setVault(findById(KeyVaultResource.class, vaultName)); } @Override public boolean refresh() { Vault vault = getVault().getKeyVault(); - KeyBundle keyBundle = vault.client().getKey(vault.vaultUri(), getName()); - if (keyBundle == null) { + Key key = vault.keys().getById(getId()); + + if (key == null) { return false; } - copyFrom(keyBundle); + copyFrom(key); return true; } @@ -225,18 +220,29 @@ public boolean refresh() { public void create(GyroUI ui, State state) throws Exception { Vault vault = getVault().getKeyVault(); - CreateKeyRequest.Builder builder = new CreateKeyRequest.Builder(vault.vaultUri(), getName(), new JsonWebKeyType(getType())); - builder.withAttributes(getAttribute().toKeyAttributes()); - builder.withKeyOperations(getOperations().stream().map(JsonWebKeyOperation::new).collect(Collectors.toList())); - builder.withKeySize(getSize()); + Key.DefinitionStages.WithCreate withCreate = vault.keys().define(getName()) + .withKeyTypeToCreate(KeyType.fromString(getType())); + + if (getSize() != null) { + withCreate = withCreate.withKeySize(getSize()); + } + + if (getAttribute() != null) { + withCreate = withCreate.withAttributes(getAttribute().toKeyProperties()); + } + + if (getOperations() != null) { + withCreate = withCreate.withKeyOperations(getOperations().stream() + .map(KeyOperation::fromString).collect(Collectors.toList())); + } if (getTags() != null) { - builder.withTags(getTags()); + withCreate = withCreate.withTags(getTags()); } - KeyBundle keyBundle = vault.client().createKey(builder.build()); + Key key = withCreate.create(); - copyFrom(keyBundle); + copyFrom(key); } @Override @@ -244,18 +250,30 @@ public void update( GyroUI ui, State state, Resource current, Set changedFieldNames) throws Exception { Vault vault = getVault().getKeyVault(); - UpdateKeyRequest.Builder builder = new UpdateKeyRequest.Builder(vault.vaultUri(), getName()); - builder.withAttributes(getAttribute().toKeyAttributes()); - builder.withKeyOperations(getOperations().stream().map(JsonWebKeyOperation::new).collect(Collectors.toList())); - builder.withTags(getTags()); + Key key = vault.keys().getById(getId()); + + Key.Update update = key.update(); + + if (changedFieldNames.contains("attribute")) { + update = update.withAttributes(getAttribute().toKeyProperties()); + } + + if (changedFieldNames.contains("operations")) { + update = update.withKeyOperations(getOperations().stream() + .map(KeyOperation::fromString).collect(Collectors.toList())); + } + + if (changedFieldNames.contains("tags")) { + update = update.withTags(getTags()); + } - vault.client().updateKey(builder.build()); + update.apply(); } @Override public void delete(GyroUI ui, State state) throws Exception { Vault vault = getVault().getKeyVault(); - vault.client().deleteKey(vault.vaultUri(), getName()); + vault.keys().deleteById(getId()); } } diff --git a/src/main/java/gyro/azure/keyvault/KeyVaultResource.java b/src/main/java/gyro/azure/keyvault/KeyVaultResource.java index 9758195a..deee04de 100644 --- a/src/main/java/gyro/azure/keyvault/KeyVaultResource.java +++ b/src/main/java/gyro/azure/keyvault/KeyVaultResource.java @@ -22,10 +22,10 @@ import java.util.Set; import java.util.stream.Collectors; -import com.microsoft.azure.CloudException; +import com.azure.core.management.Region; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.keyvault.models.Vault; import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.keyvault.Vault; -import com.microsoft.azure.management.resources.fluentcore.arm.Region; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.azure.resources.ResourceGroupResource; @@ -190,6 +190,7 @@ public class KeyVaultResource extends AzureResource implements Copyable { * The name of the key vault. */ @Required + @Id public String getName() { return name; } @@ -339,7 +340,6 @@ public void setId(String id) { /** * The URI of the key vault. */ - @Id @Output public String getUrl() { return url; @@ -381,15 +381,15 @@ public void copyFrom(Vault vault) { setEnableDeployment(vault.enabledForDeployment()); setEnableDiskEncryption(vault.enabledForDiskEncryption()); setEnableTemplateDeployment(vault.enabledForTemplateDeployment()); - setLocation(vault.inner().location()); + setLocation(vault.innerModel().location()); setEnableSoftDelete(vault.softDeleteEnabled()); } @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); - Vault vault = client.vaults().getById(getId()); + Vault vault = client.vaults().getByResourceGroup(getResourceGroup().getName(), getName()); if (vault == null) { return false; @@ -402,7 +402,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) throws Exception { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); Vault.DefinitionStages.WithCreate withCreate = client.vaults().define(getName()) .withRegion(Region.fromName(getRegion())) @@ -438,13 +438,13 @@ public void create(GyroUI ui, State state) throws Exception { setId(vault.id()); setUrl(vault.vaultUri()); - setLocation(vault.inner().location()); + setLocation(vault.innerModel().location()); } @Override public void update( GyroUI ui, State state, Resource current, Set changedFieldNames) throws Exception { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); Vault vault = client.vaults().getById(getId()); @@ -507,22 +507,22 @@ public void update( @Override public void delete(GyroUI ui, State state) throws Exception { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); client.vaults().deleteById(getId()); - try { - if (getEnablePurgeVault()) { - client.vaults().purgeDeleted(getName(), getLocation()); - } - } catch (CloudException ex) { - if (ex.body() == null || ex.body().code() == null || !ex.body().code().equals("ResourceNotFound")) { - throw ex; - } + if (getEnablePurgeVault()) { + client.vaults().purgeDeleted(getName(), getLocation()); } } Vault getKeyVault() { + AzureResourceManager client = createResourceManagerClient(); + + return client.vaults().getByResourceGroup(getResourceGroup().getName(), getName()); + } + + com.microsoft.azure.management.keyvault.Vault getOldKeyVault() { Azure client = createClient(); return client.vaults().getById(getId()); diff --git a/src/main/java/gyro/azure/keyvault/KeyVaultSecretAttribute.java b/src/main/java/gyro/azure/keyvault/KeyVaultSecretAttribute.java index ad14360b..fe06410d 100644 --- a/src/main/java/gyro/azure/keyvault/KeyVaultSecretAttribute.java +++ b/src/main/java/gyro/azure/keyvault/KeyVaultSecretAttribute.java @@ -1,14 +1,15 @@ package gyro.azure.keyvault; -import com.microsoft.azure.keyvault.models.SecretAttributes; +import java.time.OffsetDateTime; + +import com.azure.security.keyvault.secrets.models.SecretProperties; import gyro.azure.Copyable; import gyro.core.resource.Diffable; import gyro.core.resource.Output; import gyro.core.resource.Updatable; import gyro.core.validation.Required; -import org.joda.time.DateTime; -public class KeyVaultSecretAttribute extends Diffable implements Copyable { +public class KeyVaultSecretAttribute extends Diffable implements Copyable { private Boolean enabled; private String expires; private String notBefore; @@ -82,18 +83,18 @@ public String primaryKey() { } @Override - public void copyFrom(SecretAttributes attributes) { - setEnabled(attributes.enabled()); - setExpires(attributes.expires() != null ? attributes.expires().toString() : null); - setNotBefore(attributes.notBefore() != null ? attributes.notBefore().toString() : null); - setCreated(attributes.created() != null ? attributes.created().toString() : null); - setUpdated(attributes.updated() != null ? attributes.updated().toString() : null); + public void copyFrom(SecretProperties attributes) { + setEnabled(attributes.isEnabled()); + setExpires(attributes.getExpiresOn() != null ? attributes.getExpiresOn().toString() : null); + setNotBefore(attributes.getNotBefore() != null ? attributes.getNotBefore().toString() : null); + setCreated(attributes.getCreatedOn() != null ? attributes.getCreatedOn().toString() : null); + setUpdated(attributes.getUpdatedOn() != null ? attributes.getUpdatedOn().toString() : null); } - SecretAttributes toSecretAttributes() { - return (SecretAttributes) new SecretAttributes() - .withEnabled(getEnabled()) - .withExpires(getExpires() != null ? DateTime.parse(getExpires()) : null) - .withNotBefore(getNotBefore() != null ? DateTime.parse(getNotBefore()) : null); + SecretProperties toSecretProperties() { + return new SecretProperties() + .setEnabled(getEnabled()) + .setExpiresOn(getExpires() != null ? OffsetDateTime.parse(getExpires()) : null) + .setNotBefore(getNotBefore() != null ? OffsetDateTime.parse(getNotBefore()) : null); } } diff --git a/src/main/java/gyro/azure/keyvault/KeyVaultSecretResource.java b/src/main/java/gyro/azure/keyvault/KeyVaultSecretResource.java index add11161..e128c96c 100644 --- a/src/main/java/gyro/azure/keyvault/KeyVaultSecretResource.java +++ b/src/main/java/gyro/azure/keyvault/KeyVaultSecretResource.java @@ -4,12 +4,8 @@ import java.util.Map; import java.util.Set; -import com.microsoft.azure.keyvault.models.KeyVaultErrorException; -import com.microsoft.azure.keyvault.models.SecretBundle; -import com.microsoft.azure.keyvault.requests.SetSecretRequest; -import com.microsoft.azure.keyvault.requests.UpdateSecretRequest; -import com.microsoft.azure.management.keyvault.Vault; -import com.psddev.dari.util.ObjectUtils; +import com.azure.resourcemanager.keyvault.models.Secret; +import com.azure.resourcemanager.keyvault.models.Vault; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.core.GyroUI; @@ -20,6 +16,7 @@ import gyro.core.resource.Updatable; import gyro.core.scope.State; import gyro.core.validation.Required; +import org.apache.commons.lang3.StringUtils; /** * Creates a key vault secret. @@ -46,7 +43,7 @@ * end */ @Type("key-vault-secret") -public class KeyVaultSecretResource extends AzureResource implements Copyable { +public class KeyVaultSecretResource extends AzureResource implements Copyable { private String name; private KeyVaultResource vault; @@ -175,38 +172,27 @@ public void setTags(Map tags) { } @Override - public void copyFrom(SecretBundle secret) { - setName(secret.secretIdentifier().name()); + public void copyFrom(Secret secret) { + setName(secret.name()); setId(secret.id()); setKid(secret.kid()); - setIdentifier(secret.secretIdentifier().identifier()); setTags(secret.tags()); - setValue(secret.value()); + setValue(secret.getValue()); setContentType(secret.contentType()); - String vaultUri = secret.secretIdentifier().vault(); - vaultUri = vaultUri.endsWith("/") ? vaultUri : vaultUri + "/"; - setVault(findById(KeyVaultResource.class, vaultUri)); KeyVaultSecretAttribute attribute = newSubresource(KeyVaultSecretAttribute.class); attribute.copyFrom(secret.attributes()); setAttribute(attribute); + + String vaultName = getId().split(".vault.azure.net")[0].split("://")[1]; + setVault(findById(KeyVaultResource.class, vaultName)); } @Override public boolean refresh() { Vault vault = getVault().getKeyVault(); - SecretBundle secret; - - try { - secret = vault.client().getSecret(vault.vaultUri(), getName()); - } catch (KeyVaultErrorException ex) { - if (ex.body().error().message().equals("Operation get is not allowed on a disabled secret.")) { - // secret is present but in disabled state - return true; - } - throw ex; - } + Secret secret = vault.secrets().getById(getId()); if (secret == null) { return false; @@ -221,19 +207,23 @@ public boolean refresh() { public void create(GyroUI ui, State state) throws Exception { Vault vault = getVault().getKeyVault(); - SetSecretRequest.Builder builder = new SetSecretRequest.Builder(vault.vaultUri(), getName(), getValue()); + Secret.DefinitionStages.WithCreate withCreate = vault.secrets() + .define(getName()) + .withValue(getValue()); - builder.withAttributes(getAttribute().toSecretAttributes()); + if (getAttribute() != null) { + withCreate = withCreate.withAttributes(getAttribute().toSecretProperties()); + } - if (!getTags().isEmpty()) { - builder.withTags(getTags()); + if (!StringUtils.isBlank(getContentType())) { + withCreate = withCreate.withContentType(getContentType()); } - if (!ObjectUtils.isBlank(getContentType())) { - builder.withContentType(getContentType()); + if (!getTags().isEmpty()) { + withCreate = withCreate.withTags(getTags()); } - SecretBundle secret = vault.client().setSecret(builder.build()); + Secret secret = withCreate.create(); copyFrom(secret); } @@ -243,19 +233,29 @@ public void update( GyroUI ui, State state, Resource current, Set changedFieldNames) throws Exception { Vault vault = getVault().getKeyVault(); - UpdateSecretRequest.Builder builder = new UpdateSecretRequest.Builder(getId()); + Secret secret = vault.secrets().getById(getId()); - builder.withAttributes(getAttribute().toSecretAttributes()); - builder.withContentType(getContentType()); - builder.withTags(getTags()); + Secret.Update update = secret.update(); + + if (changedFieldNames.contains("attribute")) { + update = update.withAttributes(getAttribute().toSecretProperties()); + } + + if (changedFieldNames.contains("content-type")) { + update = update.withContentType(getContentType()); + } + + if (changedFieldNames.contains("tags")) { + update = update.withTags(getTags()); + } - vault.client().updateSecret(builder.build()); + update.apply(); } @Override public void delete(GyroUI ui, State state) throws Exception { Vault vault = getVault().getKeyVault(); - vault.client().deleteSecret(vault.vaultUri(), getName()); + vault.secrets().deleteById(getId()); } } From 1cd0155c75961c1d69278bfe2920730728420b3e Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Tue, 22 Feb 2022 21:15:15 -0500 Subject: [PATCH 10/43] initial dns refactor private dns moved to a different package and client, needs to implemented separately --- examples/dns/dns-zone.gyro | 1 - .../java/gyro/azure/dns/ARecordSetFinder.java | 21 +++-- .../gyro/azure/dns/ARecordSetResource.java | 33 +++---- .../gyro/azure/dns/AaaaRecordSetFinder.java | 21 +++-- .../gyro/azure/dns/AaaaRecordSetResource.java | 22 +++-- src/main/java/gyro/azure/dns/CaaRecord.java | 4 +- .../gyro/azure/dns/CaaRecordSetFinder.java | 21 +++-- .../gyro/azure/dns/CaaRecordSetResource.java | 32 ++++--- .../gyro/azure/dns/CnameRecordSetFinder.java | 21 +++-- .../azure/dns/CnameRecordSetResource.java | 31 +++---- .../java/gyro/azure/dns/DnsZoneFinder.java | 15 ++-- .../java/gyro/azure/dns/DnsZoneResource.java | 85 ++----------------- src/main/java/gyro/azure/dns/MxRecord.java | 4 +- .../gyro/azure/dns/MxRecordSetFinder.java | 21 +++-- .../gyro/azure/dns/MxRecordSetResource.java | 36 ++++---- .../gyro/azure/dns/PtrRecordSetFinder.java | 21 +++-- .../gyro/azure/dns/PtrRecordSetResource.java | 29 ++++--- src/main/java/gyro/azure/dns/SrvRecord.java | 4 +- .../gyro/azure/dns/SrvRecordSetFinder.java | 21 +++-- .../gyro/azure/dns/SrvRecordSetResource.java | 30 +++---- .../gyro/azure/dns/TxtRecordSetFinder.java | 21 +++-- .../gyro/azure/dns/TxtRecordSetResource.java | 25 +++--- 22 files changed, 243 insertions(+), 276 deletions(-) diff --git a/examples/dns/dns-zone.gyro b/examples/dns/dns-zone.gyro index f0a4305e..8b4a3a26 100644 --- a/examples/dns/dns-zone.gyro +++ b/examples/dns/dns-zone.gyro @@ -8,7 +8,6 @@ end azure::dns-zone dns-zone-example-zones name: "zones.example.com" - public-access: false resource-group: $(azure::resource-group resource-group-dns-zone-example) tags: { Name: "resource-group-dns-zone-example" diff --git a/src/main/java/gyro/azure/dns/ARecordSetFinder.java b/src/main/java/gyro/azure/dns/ARecordSetFinder.java index 5e108f76..27431ad9 100644 --- a/src/main/java/gyro/azure/dns/ARecordSetFinder.java +++ b/src/main/java/gyro/azure/dns/ARecordSetFinder.java @@ -16,11 +16,11 @@ package gyro.azure.dns; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.dns.ARecordSet; -import com.microsoft.azure.management.dns.DnsZone; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.dns.models.ARecordSet; +import com.azure.resourcemanager.dns.models.DnsZone; import com.psddev.dari.util.ObjectUtils; -import gyro.azure.AzureFinder; +import gyro.azure.AzureResourceManagerFinder; import gyro.core.GyroException; import gyro.core.Type; @@ -40,7 +40,7 @@ * a-record-set: $(external-query azure::a-record-set {}) */ @Type("a-record-set") -public class ARecordSetFinder extends AzureFinder { +public class ARecordSetFinder extends AzureResourceManagerFinder { private String dnsZoneId; private String name; @@ -67,12 +67,15 @@ public void setName(String name) { } @Override - protected List findAllAzure(Azure client) { - return client.dnsZones().list().stream().map(o -> o.aRecordSets().list()).flatMap(List::stream).collect(Collectors.toList()); + protected List findAllAzure(AzureResourceManager client) { + return client.dnsZones().list().stream() + .map(o -> o.aRecordSets().list().stream().collect(Collectors.toList())) + .flatMap(List::stream) + .collect(Collectors.toList()); } @Override - protected List findAzure(Azure client, Map filters) { + protected List findAzure(AzureResourceManager client, Map filters) { if (ObjectUtils.isBlank(filters.get("dns-zone-id"))) { throw new GyroException("'dns-zone-id' is required."); } @@ -84,7 +87,7 @@ protected List findAzure(Azure client, Map filters) if (filters.containsKey("name")) { return Collections.singletonList(dnsZone.aRecordSets().getByName(filters.get("name"))); } else { - return dnsZone.aRecordSets().list(); + return dnsZone.aRecordSets().list().stream().collect(Collectors.toList()); } } } diff --git a/src/main/java/gyro/azure/dns/ARecordSetResource.java b/src/main/java/gyro/azure/dns/ARecordSetResource.java index 48ba9a34..f54f3dc9 100644 --- a/src/main/java/gyro/azure/dns/ARecordSetResource.java +++ b/src/main/java/gyro/azure/dns/ARecordSetResource.java @@ -16,6 +16,10 @@ package gyro.azure.dns; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.dns.models.ARecordSet; +import com.azure.resourcemanager.dns.models.DnsRecordSet; +import com.azure.resourcemanager.dns.models.DnsZone; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.core.GyroUI; @@ -27,12 +31,6 @@ import com.google.common.collect.MapDifference; import com.google.common.collect.Maps; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.dns.ARecordSet; -import com.microsoft.azure.management.dns.DnsRecordSet; -import com.microsoft.azure.management.dns.DnsZone; -import com.microsoft.azure.management.dns.DnsRecordSet.UpdateDefinitionStages.ARecordSetBlank; -import com.microsoft.azure.management.dns.DnsRecordSet.UpdateDefinitionStages.WithARecordIPv4AddressOrAttachable; import gyro.core.scope.State; import gyro.core.validation.Required; @@ -162,9 +160,12 @@ public void copyFrom(ARecordSet aRecordSet) { @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); - ARecordSet aRecordSet = client.dnsZones().getById(getDnsZone().getId()).aRecordSets().getByName(getName()); + com.azure.resourcemanager.dns.models.ARecordSet aRecordSet = client.dnsZones() + .getById(getDnsZone().getId()) + .aRecordSets() + .getByName(getName()); if (aRecordSet == null) { return false; @@ -177,14 +178,16 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); - ARecordSetBlank defineARecordSetBlank = - client.dnsZones().getById(getDnsZone().getId()).update().defineARecordSet(getName()); + DnsRecordSet.UpdateDefinitionStages.ARecordSetBlank updateARecordSetBlank = client.dnsZones() + .getById(getDnsZone().getId()) + .update() + .defineARecordSet(getName()); - WithARecordIPv4AddressOrAttachable createARecordSet = null; + DnsRecordSet.UpdateDefinitionStages.WithARecordIPv4AddressOrAttachable createARecordSet = null; for (String ip : getIpv4Addresses()) { - createARecordSet = defineARecordSetBlank.withIPv4Address(ip); + createARecordSet = updateARecordSetBlank.withIPv4Address(ip); } for (Map.Entry e : getMetadata().entrySet()) { @@ -202,7 +205,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); DnsRecordSet.UpdateARecordSet updateARecordSet = client.dnsZones().getById(getDnsZone().getId()).update().updateARecordSet(getName()); @@ -251,7 +254,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); client.dnsZones().getById(getDnsZone().getId()).update().withoutARecordSet(getName()).apply(); } diff --git a/src/main/java/gyro/azure/dns/AaaaRecordSetFinder.java b/src/main/java/gyro/azure/dns/AaaaRecordSetFinder.java index be5a159d..f9cd50bf 100644 --- a/src/main/java/gyro/azure/dns/AaaaRecordSetFinder.java +++ b/src/main/java/gyro/azure/dns/AaaaRecordSetFinder.java @@ -16,11 +16,11 @@ package gyro.azure.dns; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.dns.AaaaRecordSet; -import com.microsoft.azure.management.dns.DnsZone; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.dns.models.AaaaRecordSet; +import com.azure.resourcemanager.dns.models.DnsZone; import com.psddev.dari.util.ObjectUtils; -import gyro.azure.AzureFinder; +import gyro.azure.AzureResourceManagerFinder; import gyro.core.GyroException; import gyro.core.Type; @@ -40,7 +40,7 @@ * aaaa-record-set: $(external-query azure::aaaa-record-set {}) */ @Type("aaaa-record-set") -public class AaaaRecordSetFinder extends AzureFinder { +public class AaaaRecordSetFinder extends AzureResourceManagerFinder { private String dnsZoneId; private String name; @@ -67,12 +67,15 @@ public void setName(String name) { } @Override - protected List findAllAzure(Azure client) { - return client.dnsZones().list().stream().map(o -> o.aaaaRecordSets().list()).flatMap(List::stream).collect(Collectors.toList()); + protected List findAllAzure(AzureResourceManager client) { + return client.dnsZones().list().stream() + .map(o -> o.aaaaRecordSets().list().stream().collect(Collectors.toList())) + .flatMap(List::stream) + .collect(Collectors.toList()); } @Override - protected List findAzure(Azure client, Map filters) { + protected List findAzure(AzureResourceManager client, Map filters) { if (ObjectUtils.isBlank(filters.get("dns-zone-id"))) { throw new GyroException("'dns-zone-id' is required."); } @@ -84,7 +87,7 @@ protected List findAzure(Azure client, Map filter if (filters.containsKey("name")) { return Collections.singletonList(dnsZone.aaaaRecordSets().getByName(filters.get("name"))); } else { - return dnsZone.aaaaRecordSets().list(); + return dnsZone.aaaaRecordSets().list().stream().collect(Collectors.toList()); } } } diff --git a/src/main/java/gyro/azure/dns/AaaaRecordSetResource.java b/src/main/java/gyro/azure/dns/AaaaRecordSetResource.java index b8fcdaf5..f5ffd64b 100644 --- a/src/main/java/gyro/azure/dns/AaaaRecordSetResource.java +++ b/src/main/java/gyro/azure/dns/AaaaRecordSetResource.java @@ -16,6 +16,10 @@ package gyro.azure.dns; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.dns.models.AaaaRecordSet; +import com.azure.resourcemanager.dns.models.DnsRecordSet; +import com.azure.resourcemanager.dns.models.DnsZone; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.core.GyroUI; @@ -27,12 +31,6 @@ import com.google.common.collect.MapDifference; import com.google.common.collect.Maps; -import com.microsoft.azure.management.dns.AaaaRecordSet; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.dns.DnsRecordSet; -import com.microsoft.azure.management.dns.DnsZone; -import com.microsoft.azure.management.dns.DnsRecordSet.UpdateDefinitionStages.AaaaRecordSetBlank; -import com.microsoft.azure.management.dns.DnsRecordSet.UpdateDefinitionStages.WithAaaaRecordIPv6AddressOrAttachable; import gyro.core.scope.State; import gyro.core.validation.Required; @@ -165,7 +163,7 @@ public void copyFrom(AaaaRecordSet aaaaRecordSet) { @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); AaaaRecordSet aaaaRecordSet = client.dnsZones().getById(getDnsZone().getId()).aaaaRecordSets().getByName(getName()); @@ -180,12 +178,12 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); - AaaaRecordSetBlank defineAaaaRecordSet = + DnsRecordSet.UpdateDefinitionStages.AaaaRecordSetBlank defineAaaaRecordSet = client.dnsZones().getById(getDnsZone().getId()).update().defineAaaaRecordSet(getName()); - WithAaaaRecordIPv6AddressOrAttachable createAaaaRecordSet = null; + DnsRecordSet.UpdateDefinitionStages.WithAaaaRecordIPv6AddressOrAttachable createAaaaRecordSet = null; for (String ip : getIpv6Addresses()) { createAaaaRecordSet = defineAaaaRecordSet.withIPv6Address(ip); } @@ -205,7 +203,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); DnsRecordSet.UpdateAaaaRecordSet updateAaaaRecordSet = client.dnsZones().getById(getDnsZone().getId()).update().updateAaaaRecordSet(getName()); @@ -254,7 +252,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); client.dnsZones().getById(getDnsZone().getId()).update().withoutAaaaRecordSet(getName()).apply(); } diff --git a/src/main/java/gyro/azure/dns/CaaRecord.java b/src/main/java/gyro/azure/dns/CaaRecord.java index d1c0ee85..1354254c 100644 --- a/src/main/java/gyro/azure/dns/CaaRecord.java +++ b/src/main/java/gyro/azure/dns/CaaRecord.java @@ -35,7 +35,7 @@ * value: "val1" * end */ -public class CaaRecord extends Diffable implements Copyable { +public class CaaRecord extends Diffable implements Copyable { private Integer flags; private String tag; @@ -79,7 +79,7 @@ public void setValue(String value) { } @Override - public void copyFrom(com.microsoft.azure.management.dns.CaaRecord caaRecord) { + public void copyFrom(com.azure.resourcemanager.dns.models.CaaRecord caaRecord) { setFlags(caaRecord.flags()); setTag(caaRecord.tag()); setValue(caaRecord.value()); diff --git a/src/main/java/gyro/azure/dns/CaaRecordSetFinder.java b/src/main/java/gyro/azure/dns/CaaRecordSetFinder.java index cb0cbaa5..69151a02 100644 --- a/src/main/java/gyro/azure/dns/CaaRecordSetFinder.java +++ b/src/main/java/gyro/azure/dns/CaaRecordSetFinder.java @@ -16,11 +16,11 @@ package gyro.azure.dns; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.dns.CaaRecordSet; -import com.microsoft.azure.management.dns.DnsZone; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.dns.models.CaaRecordSet; +import com.azure.resourcemanager.dns.models.DnsZone; import com.psddev.dari.util.ObjectUtils; -import gyro.azure.AzureFinder; +import gyro.azure.AzureResourceManagerFinder; import gyro.core.GyroException; import gyro.core.Type; @@ -40,7 +40,7 @@ * caa-record-set: $(external-query azure::caa-record-set {}) */ @Type("caa-record-set") -public class CaaRecordSetFinder extends AzureFinder { +public class CaaRecordSetFinder extends AzureResourceManagerFinder { private String dnsZoneId; private String name; @@ -67,12 +67,15 @@ public void setName(String name) { } @Override - protected List findAllAzure(Azure client) { - return client.dnsZones().list().stream().map(o -> o.caaRecordSets().list()).flatMap(List::stream).collect(Collectors.toList()); + protected List findAllAzure(AzureResourceManager client) { + return client.dnsZones().list().stream() + .map(o -> o.caaRecordSets().list().stream().collect(Collectors.toList())) + .flatMap(List::stream) + .collect(Collectors.toList()); } @Override - protected List findAzure(Azure client, Map filters) { + protected List findAzure(AzureResourceManager client, Map filters) { if (ObjectUtils.isBlank(filters.get("dns-zone-id"))) { throw new GyroException("'dns-zone-id' is required."); } @@ -84,7 +87,7 @@ protected List findAzure(Azure client, Map filters if (filters.containsKey("name")) { return Collections.singletonList(dnsZone.caaRecordSets().getByName(filters.get("name"))); } else { - return dnsZone.caaRecordSets().list(); + return dnsZone.caaRecordSets().list().stream().collect(Collectors.toList()); } } } diff --git a/src/main/java/gyro/azure/dns/CaaRecordSetResource.java b/src/main/java/gyro/azure/dns/CaaRecordSetResource.java index 5a85c630..dc21dea9 100644 --- a/src/main/java/gyro/azure/dns/CaaRecordSetResource.java +++ b/src/main/java/gyro/azure/dns/CaaRecordSetResource.java @@ -16,6 +16,10 @@ package gyro.azure.dns; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.dns.models.CaaRecordSet; +import com.azure.resourcemanager.dns.models.DnsRecordSet; +import com.azure.resourcemanager.dns.models.DnsZone; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.core.GyroUI; @@ -27,12 +31,6 @@ import com.google.common.collect.MapDifference; import com.google.common.collect.Maps; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.dns.CaaRecordSet; -import com.microsoft.azure.management.dns.DnsRecordSet; -import com.microsoft.azure.management.dns.DnsZone; -import com.microsoft.azure.management.dns.DnsRecordSet.UpdateDefinitionStages.WithCaaRecordEntryOrAttachable; -import com.microsoft.azure.management.dns.DnsRecordSet.UpdateDefinitionStages.CaaRecordSetBlank; import gyro.core.scope.State; import gyro.core.validation.Required; @@ -181,7 +179,7 @@ public void copyFrom(CaaRecordSet caaRecordSet) { @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); CaaRecordSet caaRecordSet = client.dnsZones().getById(getDnsZone().getId()).caaRecordSets().getByName(getName()); @@ -196,14 +194,20 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); - CaaRecordSetBlank defineCaaRecordSet = - client.dnsZones().getById(getDnsZone().getId()).update().defineCaaRecordSet(getName()); + DnsRecordSet.UpdateDefinitionStages.CaaRecordSetBlank defineCaaRecordSet = + client.dnsZones() + .getById(getDnsZone().getId()) + .update() + .defineCaaRecordSet(getName()); - WithCaaRecordEntryOrAttachable createCaaRecordSet = null; + DnsRecordSet.UpdateDefinitionStages.WithCaaRecordEntryOrAttachable createCaaRecordSet = null; for (CaaRecord caaRecord : getCaaRecord()) { - createCaaRecordSet = defineCaaRecordSet.withRecord(caaRecord.getFlags(), caaRecord.getTag(), caaRecord.getValue()); + createCaaRecordSet = defineCaaRecordSet.withRecord( + caaRecord.getFlags(), + caaRecord.getTag(), + caaRecord.getValue()); } if (getTtl() != null) { @@ -221,7 +225,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); DnsRecordSet.UpdateCaaRecordSet updateCaaRecordSet = client.dnsZones().getById(getDnsZone().getId()).update().updateCaaRecordSet(getName()); @@ -268,7 +272,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); client.dnsZones().getById(getDnsZone().getId()).update().withoutCaaRecordSet(getName()).apply(); } diff --git a/src/main/java/gyro/azure/dns/CnameRecordSetFinder.java b/src/main/java/gyro/azure/dns/CnameRecordSetFinder.java index 251ea389..0e732416 100644 --- a/src/main/java/gyro/azure/dns/CnameRecordSetFinder.java +++ b/src/main/java/gyro/azure/dns/CnameRecordSetFinder.java @@ -16,11 +16,11 @@ package gyro.azure.dns; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.dns.CNameRecordSet; -import com.microsoft.azure.management.dns.DnsZone; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.dns.models.DnsZone; +import com.azure.resourcemanager.dns.models.CnameRecordSet; import com.psddev.dari.util.ObjectUtils; -import gyro.azure.AzureFinder; +import gyro.azure.AzureResourceManagerFinder; import gyro.core.GyroException; import gyro.core.Type; @@ -40,7 +40,7 @@ * cname-record-set: $(external-query azure::cname-record-set {}) */ @Type("cname-record-set") -public class CnameRecordSetFinder extends AzureFinder { +public class CnameRecordSetFinder extends AzureResourceManagerFinder { private String dnsZoneId; private String name; @@ -67,12 +67,15 @@ public void setName(String name) { } @Override - protected List findAllAzure(Azure client) { - return client.dnsZones().list().stream().map(o -> o.cNameRecordSets().list()).flatMap(List::stream).collect(Collectors.toList()); + protected List findAllAzure(AzureResourceManager client) { + return client.dnsZones().list().stream() + .map(o -> o.cNameRecordSets().list().stream().collect(Collectors.toList())) + .flatMap(List::stream) + .collect(Collectors.toList()); } @Override - protected List findAzure(Azure client, Map filters) { + protected List findAzure(AzureResourceManager client, Map filters) { if (ObjectUtils.isBlank(filters.get("dns-zone-id"))) { throw new GyroException("'dns-zone-id' is required."); } @@ -84,7 +87,7 @@ protected List findAzure(Azure client, Map filte if (filters.containsKey("name")) { return Collections.singletonList(dnsZone.cNameRecordSets().getByName(filters.get("name"))); } else { - return dnsZone.cNameRecordSets().list(); + return dnsZone.cNameRecordSets().list().stream().collect(Collectors.toList()); } } } diff --git a/src/main/java/gyro/azure/dns/CnameRecordSetResource.java b/src/main/java/gyro/azure/dns/CnameRecordSetResource.java index 0e5d6b35..58d6789e 100644 --- a/src/main/java/gyro/azure/dns/CnameRecordSetResource.java +++ b/src/main/java/gyro/azure/dns/CnameRecordSetResource.java @@ -16,6 +16,10 @@ package gyro.azure.dns; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.dns.models.CnameRecordSet; +import com.azure.resourcemanager.dns.models.DnsRecordSet; +import com.azure.resourcemanager.dns.models.DnsZone; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.core.GyroUI; @@ -27,11 +31,6 @@ import com.google.common.collect.MapDifference; import com.google.common.collect.Maps; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.dns.CNameRecordSet; -import com.microsoft.azure.management.dns.DnsRecordSet; -import com.microsoft.azure.management.dns.DnsZone; -import com.microsoft.azure.management.dns.DnsRecordSet.UpdateDefinitionStages.WithCNameRecordSetAttachable; import gyro.core.scope.State; import gyro.core.validation.Required; @@ -55,7 +54,7 @@ * end */ @Type("cname-record-set") -public class CnameRecordSetResource extends AzureResource implements Copyable { +public class CnameRecordSetResource extends AzureResource implements Copyable { private String alias; private DnsZoneResource dnsZone; @@ -143,7 +142,7 @@ public void setId(String id) { } @Override - public void copyFrom(CNameRecordSet cnameRecordSet) { + public void copyFrom(CnameRecordSet cnameRecordSet) { setAlias(cnameRecordSet.canonicalName()); setMetadata(cnameRecordSet.metadata()); setName(cnameRecordSet.name()); @@ -154,9 +153,9 @@ public void copyFrom(CNameRecordSet cnameRecordSet) { @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); - CNameRecordSet cnameRecordSet = client.dnsZones().getById(getDnsZone().getId()).cNameRecordSets().getByName(getName()); + CnameRecordSet cnameRecordSet = client.dnsZones().getById(getDnsZone().getId()).cNameRecordSets().getByName(getName()); if (cnameRecordSet == null) { return false; @@ -169,11 +168,13 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); - WithCNameRecordSetAttachable createCNameRecordSet = - client.dnsZones().getById(getDnsZone().getId()).update(). - defineCNameRecordSet(getName()).withAlias(getAlias()); + DnsRecordSet.UpdateDefinitionStages.WithCNameRecordSetAttachable createCNameRecordSet = client.dnsZones() + .getById(getDnsZone().getId()) + .update(). + defineCNameRecordSet(getName()) + .withAlias(getAlias()); if (getTtl() != null) { createCNameRecordSet.withTimeToLive(getTtl()); @@ -190,7 +191,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); DnsRecordSet.UpdateCNameRecordSet updateCNameRecordSet = client.dnsZones().getById(getDnsZone().getId()).update().updateCNameRecordSet(getName()); @@ -229,7 +230,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); client.dnsZones().getById(getDnsZone().getId()).update().withoutCaaRecordSet(getName()).apply(); } diff --git a/src/main/java/gyro/azure/dns/DnsZoneFinder.java b/src/main/java/gyro/azure/dns/DnsZoneFinder.java index 3f18cf8c..ea798b25 100644 --- a/src/main/java/gyro/azure/dns/DnsZoneFinder.java +++ b/src/main/java/gyro/azure/dns/DnsZoneFinder.java @@ -16,16 +16,17 @@ package gyro.azure.dns; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.dns.DnsZone; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.dns.models.DnsZone; import com.psddev.dari.util.ObjectUtils; -import gyro.azure.AzureFinder; +import gyro.azure.AzureResourceManagerFinder; import gyro.core.GyroException; import gyro.core.Type; import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; /** * Query dns zone. @@ -38,7 +39,7 @@ * dns-zone: $(external-query azure::dns-zone {}) */ @Type("dns-zone") -public class DnsZoneFinder extends AzureFinder { +public class DnsZoneFinder extends AzureResourceManagerFinder { private String id; /** @@ -53,12 +54,12 @@ public void setId(String id) { } @Override - protected List findAllAzure(Azure client) { - return client.dnsZones().list(); + protected List findAllAzure(AzureResourceManager client) { + return client.dnsZones().list().stream().collect(Collectors.toList()); } @Override - protected List findAzure(Azure client, Map filters) { + protected List findAzure(AzureResourceManager client, Map filters) { if (ObjectUtils.isBlank(filters.get("id"))) { throw new GyroException("'id' is required."); } diff --git a/src/main/java/gyro/azure/dns/DnsZoneResource.java b/src/main/java/gyro/azure/dns/DnsZoneResource.java index 23adac33..def19aed 100644 --- a/src/main/java/gyro/azure/dns/DnsZoneResource.java +++ b/src/main/java/gyro/azure/dns/DnsZoneResource.java @@ -16,9 +16,10 @@ package gyro.azure.dns; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.dns.models.DnsZone; import gyro.azure.AzureResource; import gyro.azure.Copyable; -import gyro.azure.network.NetworkResource; import gyro.azure.resources.ResourceGroupResource; import gyro.core.GyroUI; import gyro.core.resource.Id; @@ -26,17 +27,12 @@ import gyro.core.resource.Output; import gyro.core.Type; import gyro.core.resource.Updatable; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.dns.DnsZone; -import com.microsoft.azure.management.dns.ZoneType; import gyro.core.scope.State; import gyro.core.validation.Required; import java.util.HashMap; -import java.util.HashSet; import java.util.Map; import java.util.Set; -import java.util.stream.Collectors; /** * Creates a DNS Zone. @@ -48,7 +44,6 @@ * * azure::dns-zone dns-zone-example-zones * name: "zones.example.com" - * public-access: false * resource-group: $(azure::resource-group resource-group-dns-zone-example) * tags: { * Name: "resource-group-dns-zone-example" @@ -59,10 +54,7 @@ public class DnsZoneResource extends AzureResource implements Copyable { private String id; - private Boolean publicAccess; private String name; - private Set registrationNetwork; - private Set resolutionNetwork; private ResourceGroupResource resourceGroup; private Map tags; @@ -79,21 +71,6 @@ public void setId(String id) { this.id = id; } - /** - * Determines if the Dns Zone is public or private. Defaults to public ``true``. - */ - public Boolean getPublicAccess() { - if (publicAccess == null) { - publicAccess = true; - } - - return publicAccess; - } - - public void setPublicAccess(Boolean publicAccess) { - this.publicAccess = publicAccess; - } - /** * The name of the Dns Zone. */ @@ -106,38 +83,6 @@ public void setName(String name) { this.name = name; } - /** - * A list of virtual network id's that register hostnames in a private Dns Zone. Can be used when the access is private. - */ - @Updatable - public Set getRegistrationNetwork() { - if (registrationNetwork == null) { - registrationNetwork = new HashSet<>(); - } - - return registrationNetwork; - } - - public void setRegistrationNetwork(Set registrationNetwork) { - this.registrationNetwork = registrationNetwork; - } - - /** - * A list of virtual network id's that resolve records in a private Dns Zone. Can be used when the access is private. - */ - @Updatable - public Set getResolutionNetwork() { - if (resolutionNetwork == null) { - resolutionNetwork = new HashSet<>(); - } - - return resolutionNetwork; - } - - public void setResolutionNetwork(Set resolutionNetwork) { - this.resolutionNetwork = resolutionNetwork; - } - /** * The Resource Group where the Dns Zone is found. */ @@ -169,17 +114,14 @@ public void setTags(Map tags) { @Override public void copyFrom(DnsZone dnsZone) { setId(dnsZone.id()); - setPublicAccess(dnsZone.accessType() == ZoneType.PUBLIC); setName(dnsZone.name()); - setRegistrationNetwork(dnsZone.registrationVirtualNetworkIds().stream().map(o -> findById(NetworkResource.class, o)).collect(Collectors.toSet())); - setResolutionNetwork(dnsZone.resolutionVirtualNetworkIds().stream().map(o -> findById(NetworkResource.class, o)).collect(Collectors.toSet())); setResourceGroup(findById(ResourceGroupResource.class, dnsZone.resourceGroupName())); setTags(dnsZone.tags()); } @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); DnsZone dnsZone = client.dnsZones().getById(getId()); @@ -194,22 +136,13 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); DnsZone.DefinitionStages.WithCreate withCreate; - withCreate = client.dnsZones().define(getName()).withExistingResourceGroup(getResourceGroup().getName()); - - if (getPublicAccess() != null && !getPublicAccess()) { - if (getRegistrationNetwork().isEmpty() && getResolutionNetwork().isEmpty()) { - withCreate.withPrivateAccess(); - } else { - withCreate.withPrivateAccess(getRegistrationNetwork().stream().map(NetworkResource::getId).collect(Collectors.toList()), - getResolutionNetwork().stream().map(NetworkResource::getId).collect(Collectors.toList())); - } - } else { - withCreate.withPublicAccess(); - } + withCreate = client.dnsZones() + .define(getName()) + .withExistingResourceGroup(getResourceGroup().getName()); withCreate.withTags(getTags()); @@ -220,7 +153,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); DnsZone.Update update = client.dnsZones().getById(getId()).update(); @@ -233,7 +166,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); client.dnsZones().deleteById(getId()); } diff --git a/src/main/java/gyro/azure/dns/MxRecord.java b/src/main/java/gyro/azure/dns/MxRecord.java index 6a0de36d..3f8e506b 100644 --- a/src/main/java/gyro/azure/dns/MxRecord.java +++ b/src/main/java/gyro/azure/dns/MxRecord.java @@ -44,7 +44,7 @@ * end * end */ -public class MxRecord extends Diffable implements Copyable { +public class MxRecord extends Diffable implements Copyable { private String exchange; private Integer preference; @@ -75,7 +75,7 @@ public void setPreference(Integer preference) { } @Override - public void copyFrom(com.microsoft.azure.management.dns.MxRecord mxRecord) { + public void copyFrom(com.azure.resourcemanager.dns.models.MxRecord mxRecord) { setExchange(mxRecord.exchange()); setPreference(mxRecord.preference()); } diff --git a/src/main/java/gyro/azure/dns/MxRecordSetFinder.java b/src/main/java/gyro/azure/dns/MxRecordSetFinder.java index 4db19f00..ac8527da 100644 --- a/src/main/java/gyro/azure/dns/MxRecordSetFinder.java +++ b/src/main/java/gyro/azure/dns/MxRecordSetFinder.java @@ -16,11 +16,11 @@ package gyro.azure.dns; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.dns.MXRecordSet; -import com.microsoft.azure.management.dns.DnsZone; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.dns.models.DnsZone; +import com.azure.resourcemanager.dns.models.MxRecordSet; import com.psddev.dari.util.ObjectUtils; -import gyro.azure.AzureFinder; +import gyro.azure.AzureResourceManagerFinder; import gyro.core.GyroException; import gyro.core.Type; @@ -40,7 +40,7 @@ * mx-record-set: $(external-query azure::mx-record-set {}) */ @Type("mx-record-set") -public class MxRecordSetFinder extends AzureFinder { +public class MxRecordSetFinder extends AzureResourceManagerFinder { private String dnsZoneId; private String name; @@ -67,12 +67,15 @@ public void setName(String name) { } @Override - protected List findAllAzure(Azure client) { - return client.dnsZones().list().stream().map(o -> o.mxRecordSets().list()).flatMap(List::stream).collect(Collectors.toList()); + protected List findAllAzure(AzureResourceManager client) { + return client.dnsZones().list().stream() + .map(o -> o.mxRecordSets().list().stream().collect(Collectors.toList())) + .flatMap(List::stream) + .collect(Collectors.toList()); } @Override - protected List findAzure(Azure client, Map filters) { + protected List findAzure(AzureResourceManager client, Map filters) { if (ObjectUtils.isBlank(filters.get("dns-zone-id"))) { throw new GyroException("'dns-zone-id' is required."); } @@ -84,7 +87,7 @@ protected List findAzure(Azure client, Map filters) if (filters.containsKey("name")) { return Collections.singletonList(dnsZone.mxRecordSets().getByName(filters.get("name"))); } else { - return dnsZone.mxRecordSets().list(); + return dnsZone.mxRecordSets().list().stream().collect(Collectors.toList()); } } } diff --git a/src/main/java/gyro/azure/dns/MxRecordSetResource.java b/src/main/java/gyro/azure/dns/MxRecordSetResource.java index 07ee8967..b2e24ae1 100644 --- a/src/main/java/gyro/azure/dns/MxRecordSetResource.java +++ b/src/main/java/gyro/azure/dns/MxRecordSetResource.java @@ -16,6 +16,10 @@ package gyro.azure.dns; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.dns.models.DnsRecordSet; +import com.azure.resourcemanager.dns.models.DnsZone; +import com.azure.resourcemanager.dns.models.MxRecordSet; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.core.GyroUI; @@ -27,12 +31,6 @@ import com.google.common.collect.MapDifference; import com.google.common.collect.Maps; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.dns.DnsRecordSet; -import com.microsoft.azure.management.dns.DnsZone; -import com.microsoft.azure.management.dns.MXRecordSet; -import com.microsoft.azure.management.dns.DnsRecordSet.UpdateDefinitionStages.MXRecordSetBlank; -import com.microsoft.azure.management.dns.DnsRecordSet.UpdateDefinitionStages.WithMXRecordMailExchangeOrAttachable; import gyro.core.scope.State; import gyro.core.validation.Required; @@ -69,7 +67,7 @@ * end */ @Type("mx-record-set") -public class MxRecordSetResource extends AzureResource implements Copyable { +public class MxRecordSetResource extends AzureResource implements Copyable { private DnsZoneResource dnsZone; private Set mxRecord; @@ -164,7 +162,7 @@ public void setId(String id) { } @Override - public void copyFrom(MXRecordSet mxRecordSet) { + public void copyFrom(MxRecordSet mxRecordSet) { setMxRecord(mxRecordSet.records().stream().map(o -> { MxRecord mxRecord = newSubresource(MxRecord.class); mxRecord.copyFrom(o); @@ -179,9 +177,9 @@ public void copyFrom(MXRecordSet mxRecordSet) { @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); - MXRecordSet mxRecordSet = client.dnsZones().getById(getDnsZone().getId()).mxRecordSets().getByName(getName()); + MxRecordSet mxRecordSet = client.dnsZones().getById(getDnsZone().getId()).mxRecordSets().getByName(getName()); if (mxRecordSet == null) { return false; @@ -194,14 +192,18 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); - MXRecordSetBlank defineMXRecordSet = - client.dnsZones().getById(getDnsZone().getId()).update().defineMXRecordSet(getName()); + DnsRecordSet.UpdateDefinitionStages.MXRecordSetBlank defineMXRecordSet = client.dnsZones() + .getById(getDnsZone().getId()) + .update() + .defineMXRecordSet(getName()); - WithMXRecordMailExchangeOrAttachable createMXRecordSet = null; + DnsRecordSet.UpdateDefinitionStages.WithMXRecordMailExchangeOrAttachable createMXRecordSet = null; for (MxRecord mxRecord : getMxRecord()) { - createMXRecordSet = defineMXRecordSet.withMailExchange(mxRecord.getExchange(), mxRecord.getPreference()); + createMXRecordSet = defineMXRecordSet.withMailExchange( + mxRecord.getExchange(), + mxRecord.getPreference()); } if (getTtl() != null) { @@ -219,7 +221,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); DnsRecordSet.UpdateMXRecordSet updateMXRecordSet = client.dnsZones().getById(getDnsZone().getId()).update().updateMXRecordSet(getName()); @@ -279,7 +281,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); client.dnsZones().getById(getDnsZone().getId()).update().withoutMXRecordSet(getName()).apply(); } diff --git a/src/main/java/gyro/azure/dns/PtrRecordSetFinder.java b/src/main/java/gyro/azure/dns/PtrRecordSetFinder.java index fc86fd12..d9e04642 100644 --- a/src/main/java/gyro/azure/dns/PtrRecordSetFinder.java +++ b/src/main/java/gyro/azure/dns/PtrRecordSetFinder.java @@ -16,11 +16,11 @@ package gyro.azure.dns; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.dns.PtrRecordSet; -import com.microsoft.azure.management.dns.DnsZone; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.dns.models.DnsZone; +import com.azure.resourcemanager.dns.models.PtrRecordSet; import com.psddev.dari.util.ObjectUtils; -import gyro.azure.AzureFinder; +import gyro.azure.AzureResourceManagerFinder; import gyro.core.GyroException; import gyro.core.Type; @@ -40,7 +40,7 @@ * ptr-record-set: $(external-query azure::ptr-record-set {}) */ @Type("ptr-record-set") -public class PtrRecordSetFinder extends AzureFinder { +public class PtrRecordSetFinder extends AzureResourceManagerFinder { private String dnsZoneId; private String name; @@ -67,12 +67,15 @@ public void setName(String name) { } @Override - protected List findAllAzure(Azure client) { - return client.dnsZones().list().stream().map(o -> o.ptrRecordSets().list()).flatMap(List::stream).collect(Collectors.toList()); + protected List findAllAzure(AzureResourceManager client) { + return client.dnsZones().list().stream() + .map(o -> o.ptrRecordSets().list().stream().collect(Collectors.toList())) + .flatMap(List::stream) + .collect(Collectors.toList()); } @Override - protected List findAzure(Azure client, Map filters) { + protected List findAzure(AzureResourceManager client, Map filters) { if (ObjectUtils.isBlank(filters.get("dns-zone-id"))) { throw new GyroException("'dns-zone-id' is required."); } @@ -84,7 +87,7 @@ protected List findAzure(Azure client, Map filters if (filters.containsKey("name")) { return Collections.singletonList(dnsZone.ptrRecordSets().getByName(filters.get("name"))); } else { - return dnsZone.ptrRecordSets().list(); + return dnsZone.ptrRecordSets().list().stream().collect(Collectors.toList()); } } } diff --git a/src/main/java/gyro/azure/dns/PtrRecordSetResource.java b/src/main/java/gyro/azure/dns/PtrRecordSetResource.java index 23fabd4d..8fcd9b71 100644 --- a/src/main/java/gyro/azure/dns/PtrRecordSetResource.java +++ b/src/main/java/gyro/azure/dns/PtrRecordSetResource.java @@ -16,6 +16,10 @@ package gyro.azure.dns; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.dns.models.DnsRecordSet; +import com.azure.resourcemanager.dns.models.DnsZone; +import com.azure.resourcemanager.dns.models.PtrRecordSet; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.core.GyroUI; @@ -27,12 +31,6 @@ import com.google.common.collect.MapDifference; import com.google.common.collect.Maps; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.dns.DnsRecordSet; -import com.microsoft.azure.management.dns.DnsZone; -import com.microsoft.azure.management.dns.PtrRecordSet; -import com.microsoft.azure.management.dns.DnsRecordSet.UpdateDefinitionStages.PtrRecordSetBlank; -import com.microsoft.azure.management.dns.DnsRecordSet.UpdateDefinitionStages.WithPtrRecordTargetDomainNameOrAttachable; import gyro.core.scope.State; import gyro.core.validation.Required; @@ -163,7 +161,7 @@ public void copyFrom(PtrRecordSet ptrRecordSet) { @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); PtrRecordSet ptrRecordSet = client.dnsZones().getById(getDnsZone().getId()).ptrRecordSets().getByName(getName()); @@ -177,14 +175,17 @@ public boolean refresh() { } public void create(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); - PtrRecordSetBlank definePtrRecordSet = - client.dnsZones().getById(getDnsZone().getId()).update().definePtrRecordSet(getName()); + DnsRecordSet.UpdateDefinitionStages.PtrRecordSetBlank definePtrRecordSet = client.dnsZones() + .getById(getDnsZone().getId()) + .update() + .definePtrRecordSet(getName()); - WithPtrRecordTargetDomainNameOrAttachable createPtrRecordSet = null; + DnsRecordSet.UpdateDefinitionStages.WithPtrRecordTargetDomainNameOrAttachable createPtrRecordSet = null; for (String targetDomainName : getTargetDomainNames()) { - createPtrRecordSet = definePtrRecordSet.withTargetDomainName(targetDomainName); + createPtrRecordSet = definePtrRecordSet.withTargetDomainName( + targetDomainName); } if (getTtl() != null) { @@ -202,7 +203,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); DnsRecordSet.UpdatePtrRecordSet updatePtrRecordSet = client.dnsZones().getById(getDnsZone().getId()).update().updatePtrRecordSet(getName()); @@ -251,7 +252,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); client.dnsZones().getById(getDnsZone().getId()).update().withoutPtrRecordSet(getName()).apply(); } diff --git a/src/main/java/gyro/azure/dns/SrvRecord.java b/src/main/java/gyro/azure/dns/SrvRecord.java index 46476da2..59c39163 100644 --- a/src/main/java/gyro/azure/dns/SrvRecord.java +++ b/src/main/java/gyro/azure/dns/SrvRecord.java @@ -35,7 +35,7 @@ * weight: 100 * end */ -public class SrvRecord extends Diffable implements Copyable { +public class SrvRecord extends Diffable implements Copyable { private Integer port; private Integer priority; @@ -91,7 +91,7 @@ public void setWeight(Integer weight) { } @Override - public void copyFrom(com.microsoft.azure.management.dns.SrvRecord srvRecord) { + public void copyFrom(com.azure.resourcemanager.dns.models.SrvRecord srvRecord) { setPort(srvRecord.port()); setPriority(srvRecord.priority()); setTarget(srvRecord.target()); diff --git a/src/main/java/gyro/azure/dns/SrvRecordSetFinder.java b/src/main/java/gyro/azure/dns/SrvRecordSetFinder.java index 7071c0ca..ec1f3878 100644 --- a/src/main/java/gyro/azure/dns/SrvRecordSetFinder.java +++ b/src/main/java/gyro/azure/dns/SrvRecordSetFinder.java @@ -16,11 +16,11 @@ package gyro.azure.dns; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.dns.SrvRecordSet; -import com.microsoft.azure.management.dns.DnsZone; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.dns.models.DnsZone; +import com.azure.resourcemanager.dns.models.SrvRecordSet; import com.psddev.dari.util.ObjectUtils; -import gyro.azure.AzureFinder; +import gyro.azure.AzureResourceManagerFinder; import gyro.core.GyroException; import gyro.core.Type; @@ -40,7 +40,7 @@ * srv-record-set: $(external-query azure::srv-record-set {}) */ @Type("srv-record-set") -public class SrvRecordSetFinder extends AzureFinder { +public class SrvRecordSetFinder extends AzureResourceManagerFinder { private String dnsZoneId; private String name; @@ -67,12 +67,15 @@ public void setName(String name) { } @Override - protected List findAllAzure(Azure client) { - return client.dnsZones().list().stream().map(o -> o.srvRecordSets().list()).flatMap(List::stream).collect(Collectors.toList()); + protected List findAllAzure(AzureResourceManager client) { + return client.dnsZones().list().stream() + .map(o -> o.srvRecordSets().list().stream().collect(Collectors.toList())) + .flatMap(List::stream) + .collect(Collectors.toList()); } @Override - protected List findAzure(Azure client, Map filters) { + protected List findAzure(AzureResourceManager client, Map filters) { if (ObjectUtils.isBlank(filters.get("dns-zone-id"))) { throw new GyroException("'dns-zone-id' is required."); } @@ -84,7 +87,7 @@ protected List findAzure(Azure client, Map filters if (filters.containsKey("name")) { return Collections.singletonList(dnsZone.srvRecordSets().getByName(filters.get("name"))); } else { - return dnsZone.srvRecordSets().list(); + return dnsZone.srvRecordSets().list().stream().collect(Collectors.toList()); } } } diff --git a/src/main/java/gyro/azure/dns/SrvRecordSetResource.java b/src/main/java/gyro/azure/dns/SrvRecordSetResource.java index c9b31f08..9a62690d 100644 --- a/src/main/java/gyro/azure/dns/SrvRecordSetResource.java +++ b/src/main/java/gyro/azure/dns/SrvRecordSetResource.java @@ -16,6 +16,11 @@ package gyro.azure.dns; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.dns.models.DnsRecordSet; +import com.azure.resourcemanager.dns.models.DnsZone; +import com.azure.resourcemanager.dns.models.SrvRecordSet; +import com.google.common.collect.Maps; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.core.GyroUI; @@ -26,13 +31,6 @@ import gyro.core.resource.Updatable; import com.google.common.collect.MapDifference; -import com.google.common.collect.Maps; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.dns.DnsRecordSet; -import com.microsoft.azure.management.dns.DnsZone; -import com.microsoft.azure.management.dns.SrvRecordSet; -import com.microsoft.azure.management.dns.DnsRecordSet.UpdateDefinitionStages.WithSrvRecordEntryOrAttachable; -import com.microsoft.azure.management.dns.DnsRecordSet.UpdateDefinitionStages.SrvRecordSetBlank; import gyro.core.scope.State; import gyro.core.validation.Required; @@ -176,7 +174,7 @@ public void copyFrom(SrvRecordSet srvRecordSet) { @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); SrvRecordSet srvRecordSet = client.dnsZones().getById(getDnsZone().getId()).srvRecordSets().getByName(getName()); @@ -191,15 +189,17 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); - SrvRecordSetBlank defineSrvRecordSet = - client.dnsZones().getById(getDnsZone().getId()).update().defineSrvRecordSet(getName()); + DnsRecordSet.UpdateDefinitionStages.SrvRecordSetBlank defineSrvRecordSet = client.dnsZones() + .getById(getDnsZone().getId()) + .update() + .defineSrvRecordSet(getName()); - WithSrvRecordEntryOrAttachable createSrvRecordSet = null; + DnsRecordSet.UpdateDefinitionStages.WithSrvRecordEntryOrAttachable createSrvRecordSet = null; for (SrvRecord srvRecord : getSrvRecord()) { createSrvRecordSet = defineSrvRecordSet - .withRecord(srvRecord.getTarget(), srvRecord.getPort(), srvRecord.getPriority(), srvRecord.getWeight()); + .withRecord(srvRecord.getTarget(), srvRecord.getPort(), srvRecord.getPriority(), srvRecord.getWeight()); } if (getTtl() != null) { @@ -216,7 +216,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); DnsRecordSet.UpdateSrvRecordSet updateSrvRecordSet = client.dnsZones().getById(getDnsZone().getId()).update().updateSrvRecordSet(getName()); @@ -262,7 +262,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); client.dnsZones().getById(getDnsZone().getId()).update().withoutSrvRecordSet(getName()).apply(); } diff --git a/src/main/java/gyro/azure/dns/TxtRecordSetFinder.java b/src/main/java/gyro/azure/dns/TxtRecordSetFinder.java index 241fabd1..2b02f028 100644 --- a/src/main/java/gyro/azure/dns/TxtRecordSetFinder.java +++ b/src/main/java/gyro/azure/dns/TxtRecordSetFinder.java @@ -16,11 +16,11 @@ package gyro.azure.dns; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.dns.TxtRecordSet; -import com.microsoft.azure.management.dns.DnsZone; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.dns.models.DnsZone; +import com.azure.resourcemanager.dns.models.TxtRecordSet; import com.psddev.dari.util.ObjectUtils; -import gyro.azure.AzureFinder; +import gyro.azure.AzureResourceManagerFinder; import gyro.core.GyroException; import gyro.core.Type; @@ -40,7 +40,7 @@ * txt-record-set: $(external-query azure::txt-record-set {}) */ @Type("txt-record-set") -public class TxtRecordSetFinder extends AzureFinder { +public class TxtRecordSetFinder extends AzureResourceManagerFinder { private String dnsZoneId; private String name; @@ -67,12 +67,15 @@ public void setName(String name) { } @Override - protected List findAllAzure(Azure client) { - return client.dnsZones().list().stream().map(o -> o.txtRecordSets().list()).flatMap(List::stream).collect(Collectors.toList()); + protected List findAllAzure(AzureResourceManager client) { + return client.dnsZones().list().stream() + .map(o -> o.txtRecordSets().list().stream().collect(Collectors.toList())) + .flatMap(List::stream) + .collect(Collectors.toList()); } @Override - protected List findAzure(Azure client, Map filters) { + protected List findAzure(AzureResourceManager client, Map filters) { if (ObjectUtils.isBlank(filters.get("dns-zone-id"))) { throw new GyroException("'dns-zone-id' is required."); } @@ -84,7 +87,7 @@ protected List findAzure(Azure client, Map filters if (filters.containsKey("name")) { return Collections.singletonList(dnsZone.txtRecordSets().getByName(filters.get("name"))); } else { - return dnsZone.txtRecordSets().list(); + return dnsZone.txtRecordSets().list().stream().collect(Collectors.toList()); } } } diff --git a/src/main/java/gyro/azure/dns/TxtRecordSetResource.java b/src/main/java/gyro/azure/dns/TxtRecordSetResource.java index e7dec566..7be02092 100644 --- a/src/main/java/gyro/azure/dns/TxtRecordSetResource.java +++ b/src/main/java/gyro/azure/dns/TxtRecordSetResource.java @@ -16,6 +16,10 @@ package gyro.azure.dns; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.dns.models.DnsRecordSet; +import com.azure.resourcemanager.dns.models.DnsZone; +import com.azure.resourcemanager.dns.models.TxtRecordSet; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.core.GyroUI; @@ -27,11 +31,6 @@ import com.google.common.collect.MapDifference; import com.google.common.collect.Maps; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.dns.DnsRecordSet; -import com.microsoft.azure.management.dns.DnsRecordSet.UpdateDefinitionStages.WithTxtRecordTextValueOrAttachable; -import com.microsoft.azure.management.dns.DnsZone; -import com.microsoft.azure.management.dns.TxtRecordSet; import gyro.core.scope.State; import gyro.core.validation.Required; @@ -163,7 +162,7 @@ public void copyFrom(TxtRecordSet txtRecordSet) { @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); TxtRecordSet txtRecordSet = client.dnsZones().getById(getDnsZone().getId()).txtRecordSets().getByName(getName()); @@ -178,12 +177,14 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); - DnsRecordSet.UpdateDefinitionStages.TxtRecordSetBlank defineTxtRecordSet = - client.dnsZones().getById(getDnsZone().getId()).update().defineTxtRecordSet(getName()); + DnsRecordSet.UpdateDefinitionStages.TxtRecordSetBlank defineTxtRecordSet = client.dnsZones() + .getById(getDnsZone().getId()) + .update() + .defineTxtRecordSet(getName()); - WithTxtRecordTextValueOrAttachable createTxtRecordSet = null; + DnsRecordSet.UpdateDefinitionStages.WithTxtRecordTextValueOrAttachable createTxtRecordSet = null; for (String txtRecord : getTxtRecords()) { createTxtRecordSet = defineTxtRecordSet.withText(txtRecord); } @@ -203,7 +204,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); DnsRecordSet.UpdateTxtRecordSet updateTxtRecordSet = client.dnsZones().getById(getDnsZone().getId()).update().updateTxtRecordSet(getName()); @@ -252,7 +253,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); client.dnsZones().getById(getDnsZone().getId()).update().withoutTxtRecordSet(getName()).apply(); } From c5725d8d0f7a06d0e0ceefd4366f882a0ed08958 Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Mon, 7 Mar 2022 16:29:48 -0500 Subject: [PATCH 11/43] Add service access point for Kubernetes Cluster --- .../ApiServerAccessProfile.java | 113 ++++++++++++++++++ .../KubernetesClusterResource.java | 68 +++++++++-- 2 files changed, 170 insertions(+), 11 deletions(-) create mode 100644 src/main/java/gyro/azure/containerservice/ApiServerAccessProfile.java diff --git a/src/main/java/gyro/azure/containerservice/ApiServerAccessProfile.java b/src/main/java/gyro/azure/containerservice/ApiServerAccessProfile.java new file mode 100644 index 00000000..1fa8149c --- /dev/null +++ b/src/main/java/gyro/azure/containerservice/ApiServerAccessProfile.java @@ -0,0 +1,113 @@ +package gyro.azure.containerservice; + +import java.util.ArrayList; +import java.util.List; + +import com.azure.resourcemanager.containerservice.models.ManagedClusterApiServerAccessProfile; +import gyro.azure.Copyable; +import gyro.core.resource.Diffable; +import gyro.core.validation.ValidStrings; + +public class ApiServerAccessProfile extends Diffable implements Copyable { + + private Boolean enablePrivateCluster; + private Boolean enablePrivateClusterPublicFqdn; + private Boolean disableRunCommand; + private String privateDnsZone; + private List authorizedIpRanges; + + /** + * Enable private cluster. + */ + public Boolean getEnablePrivateCluster() { + return enablePrivateCluster; + } + + public void setEnablePrivateCluster(Boolean enablePrivateCluster) { + this.enablePrivateCluster = enablePrivateCluster; + } + + /** + * When set to ``true`` enables public fqdn on the private cluster. + */ + public Boolean getEnablePrivateClusterPublicFqdn() { + return enablePrivateClusterPublicFqdn; + } + + public void setEnablePrivateClusterPublicFqdn(Boolean enablePrivateClusterPublicFqdn) { + this.enablePrivateClusterPublicFqdn = enablePrivateClusterPublicFqdn; + } + + /** + * If set ot ``true`` disables run command. + */ + public Boolean getDisableRunCommand() { + return disableRunCommand; + } + + public void setDisableRunCommand(Boolean disableRunCommand) { + this.disableRunCommand = disableRunCommand; + } + + /** + * The private dns mode. + */ + @ValidStrings({"system", "none"}) + public String getPrivateDnsZone() { + return privateDnsZone; + } + + public void setPrivateDnsZone(String privateDnsZone) { + this.privateDnsZone = privateDnsZone; + } + + /** + * A list of authorized Ips. + */ + public List getAuthorizedIpRanges() { + if (authorizedIpRanges == null) { + authorizedIpRanges = new ArrayList<>(); + } + + return authorizedIpRanges; + } + + public void setAuthorizedIpRanges(List authorizedIpRanges) { + this.authorizedIpRanges = authorizedIpRanges; + } + + @Override + public void copyFrom(ManagedClusterApiServerAccessProfile model) { + setEnablePrivateCluster(model.enablePrivateCluster()); + setDisableRunCommand(model.disableRunCommand()); + setEnablePrivateClusterPublicFqdn(model.enablePrivateClusterPublicFqdn()); + setAuthorizedIpRanges(model.authorizedIpRanges()); + setPrivateDnsZone(model.privateDnsZone()); + } + + @Override + public String primaryKey() { + return ""; + } + + protected ManagedClusterApiServerAccessProfile toManagedClusterApiServerAccessProfile() { + return new ManagedClusterApiServerAccessProfile() + .withEnablePrivateCluster(getEnablePrivateCluster()) + .withAuthorizedIpRanges(getAuthorizedIpRanges()) + .withDisableRunCommand(getDisableRunCommand()) + .withEnablePrivateClusterPublicFqdn(getEnablePrivateClusterPublicFqdn()) + .withPrivateDnsZone(getPrivateDnsZone()); + } + + static protected ManagedClusterApiServerAccessProfile defaultPublic() { + return new ManagedClusterApiServerAccessProfile() + .withEnablePrivateCluster(false); + } + + static protected ManagedClusterApiServerAccessProfile defaultPrivate() { + return new ManagedClusterApiServerAccessProfile() + .withEnablePrivateCluster(true) + .withEnablePrivateClusterPublicFqdn(true) + .withPrivateDnsZone("system"); + } +} diff --git a/src/main/java/gyro/azure/containerservice/KubernetesClusterResource.java b/src/main/java/gyro/azure/containerservice/KubernetesClusterResource.java index d22d7286..8dfebd69 100644 --- a/src/main/java/gyro/azure/containerservice/KubernetesClusterResource.java +++ b/src/main/java/gyro/azure/containerservice/KubernetesClusterResource.java @@ -17,6 +17,7 @@ import com.azure.resourcemanager.containerservice.models.KubernetesClusterAgentPool; import com.azure.resourcemanager.containerservice.models.KubernetesClusters; import com.azure.resourcemanager.containerservice.models.ManagedClusterAddonProfile; +import com.azure.resourcemanager.containerservice.models.ManagedClusterApiServerAccessProfile; import com.azure.resourcemanager.containerservice.models.OSDiskType; import com.azure.resourcemanager.containerservice.models.OSType; import com.azure.resourcemanager.containerservice.models.PublicNetworkAccess; @@ -42,7 +43,7 @@ import org.apache.commons.lang3.StringUtils; /** - * Creates a Identity. + * Creates a Kubernetes Cluster. * * Example * ------- @@ -104,12 +105,8 @@ * Name: "kubernetes-cluster-example" * } * - * * end * - * - * - * */ @Type("kubernetes-cluster") public class KubernetesClusterResource extends AzureResource implements Copyable { @@ -135,6 +132,7 @@ public class KubernetesClusterResource extends AzureResource implements Copyable private Map tags; private Boolean enablePrivateCluster; private ClusterPropertiesAutoScalerProfile autoScalerProfile; + private ApiServerAccessProfile apiServerAccessProfile; /** * Name of the cluster. @@ -402,6 +400,20 @@ public void setAutoScalerProfile(ClusterPropertiesAutoScalerProfile autoScalerPr this.autoScalerProfile = autoScalerProfile; } + /** + * Api server access profile config. + * + * @subresource gyro.azure.containerservice.ApiServerAccessProfile + */ + @Updatable + public ApiServerAccessProfile getApiServerAccessProfile() { + return apiServerAccessProfile; + } + + public void setApiServerAccessProfile(ApiServerAccessProfile apiServerAccessProfile) { + this.apiServerAccessProfile = apiServerAccessProfile; + } + @Override public void copyFrom(KubernetesCluster cluster) { setName(cluster.name()); @@ -420,8 +432,8 @@ public void copyFrom(KubernetesCluster cluster) { setId(cluster.id()); setResourceGroup(findById(ResourceGroupResource.class, cluster.resourceGroupName())); setTags(cluster.tags()); - setEnablePrivateCluster(cluster.innerModel().publicNetworkAccess() != null ? cluster.innerModel().publicNetworkAccess().equals(PublicNetworkAccess.DISABLED) : null); - + setEnablePrivateCluster(cluster.innerModel().publicNetworkAccess() == null + || cluster.innerModel().publicNetworkAccess().equals(PublicNetworkAccess.DISABLED)); Set addonProfiles = new HashSet<>(); try { @@ -463,6 +475,17 @@ public void copyFrom(KubernetesCluster cluster) { autoScalerProfile.copyFrom(cluster.innerModel().autoScalerProfile()); } setAutoScalerProfile(autoScalerProfile); + + ApiServerAccessProfile apiServerAccessProfile = null; + if (cluster.innerModel().apiServerAccessProfile() != null) { + apiServerAccessProfile = newSubresource(ApiServerAccessProfile.class); + apiServerAccessProfile.copyFrom(cluster.innerModel().apiServerAccessProfile()); + + if (apiServerAccessProfile.getEnablePrivateCluster() != null) { + setEnablePrivateCluster(apiServerAccessProfile.getEnablePrivateCluster()); + } + } + setApiServerAccessProfile(apiServerAccessProfile); } @Override @@ -474,8 +497,10 @@ public boolean refresh() { .filter(o -> o.resourceGroupName().equals(getResourceGroup().getName())) .findFirst().orElse(null); + boolean privateCluster = getEnablePrivateCluster(); if (cluster != null) { copyFrom(cluster); + setEnablePrivateCluster(privateCluster); return true; } @@ -513,7 +538,7 @@ public void create(GyroUI ui, State state) throws Exception { createStage = withCreate.defineAgentPool(agentPool.getName()); } - WithAttach withAttach = createStage + WithAttach withAttach = createStage .withVirtualMachineSize(ContainerServiceVMSizeTypes.fromString(agentPool.getSize())) .withAgentPoolVirtualMachineCount(agentPool.getCount()) @@ -572,13 +597,19 @@ public void create(GyroUI ui, State state) throws Exception { KubernetesCluster cluster = withCreate.create(); setId(cluster.id()); + state.save(); - KubernetesCluster.Update update = cluster.update(); + KubernetesCluster.Update update; + if (getApiServerAccessProfile() != null) { + cluster.innerModel() + .withApiServerAccessProfile(getApiServerAccessProfile().toManagedClusterApiServerAccessProfile()); + } + + update = cluster.update(); if (getNetworkProfile() != null) { NetworkProfile networkProfile = getNetworkProfile(); setNetworkProfile(null); - state.save(); setNetworkProfile(networkProfile); update = update.withNetworkProfile(getNetworkProfile().toNetworkProfile()); } @@ -603,8 +634,23 @@ public void update( KubernetesCluster cluster = client.kubernetesClusters() .getByResourceGroup(getResourceGroup().getName(), getName()); - KubernetesCluster.Update update = cluster.update(); + KubernetesCluster.Update update = null; + if (changedFieldNames.contains("api-server-access-profile")) { + if (getApiServerAccessProfile() != null) { + cluster.innerModel() + .withApiServerAccessProfile(getApiServerAccessProfile().toManagedClusterApiServerAccessProfile()); + } else { + if (getEnablePrivateCluster()) { + cluster.innerModel() + .withApiServerAccessProfile(ApiServerAccessProfile.defaultPrivate()); + } else { + cluster.innerModel() + .withApiServerAccessProfile(ApiServerAccessProfile.defaultPublic()); + } + } + } + update = cluster.update(); if (changedFieldNames.contains("enable-rbac")) { if (getEnableRbac()) { From 54c5c509954414ba6fddcc9e00ab373c75806eb9 Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Mon, 7 Mar 2022 16:30:20 -0500 Subject: [PATCH 12/43] Update validation for container service --- src/main/java/gyro/azure/containerservice/NetworkProfile.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/gyro/azure/containerservice/NetworkProfile.java b/src/main/java/gyro/azure/containerservice/NetworkProfile.java index 03d9c7e8..ebc067c3 100644 --- a/src/main/java/gyro/azure/containerservice/NetworkProfile.java +++ b/src/main/java/gyro/azure/containerservice/NetworkProfile.java @@ -108,7 +108,7 @@ public void setLoadBalancerProfile(ClusterLoadBalancerProfile loadBalancerProfil * The load balancer sku for the network profile. */ @Updatable - @ValidStrings({"standard", "basic"}) + @ValidStrings({"Standard", "Basic"}) public String getLoadBalancerSku() { return loadBalancerSku; } From 078d03579534cd187edf767ab92aaaf351efeee1 Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Mon, 7 Mar 2022 16:31:42 -0500 Subject: [PATCH 13/43] Update validation for storage --- .../gyro/azure/storage/CloudBlobContainerResource.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/gyro/azure/storage/CloudBlobContainerResource.java b/src/main/java/gyro/azure/storage/CloudBlobContainerResource.java index 847025da..111d1f39 100644 --- a/src/main/java/gyro/azure/storage/CloudBlobContainerResource.java +++ b/src/main/java/gyro/azure/storage/CloudBlobContainerResource.java @@ -46,7 +46,7 @@ * * azure::cloud-blob-container blob-container-example * name: "blobcontainer" - * public-access: "CONTAINER" + * public-access: "Container" * storage-account: $(azure::storage-account blob-storage-account-example) * end */ @@ -73,10 +73,10 @@ public void setName(String name) { } /** - * The public access of the container. Valid values are ``Blob`` or ``Container`` or ``Off`` + * The public access of the container. Valid values are ``Blob`` or ``Container`` or ``None`` */ @Required - @ValidStrings({"Blob", "Container", "Off"}) + @ValidStrings({"Blob", "Container", "None"}) @Updatable public String getPublicAccess() { return publicAccess; @@ -124,7 +124,7 @@ public void setId(String id) { @Override public void copyFrom(BlobContainer container) { - setPublicAccess(container.publicAccess().toString()); + setPublicAccess(container.publicAccess() != null ? container.publicAccess().toString() : "None"); setName(container.name()); setId(container.id()); setMetadata(container.metadata()); From 9dd4a04079f3a37ec2fdc24ae752f980dd1cdaa8 Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Wed, 23 Mar 2022 12:57:50 -0400 Subject: [PATCH 14/43] Add output fields nsrecords and nameservers for Dns Zone --- .../java/gyro/azure/dns/DnsZoneResource.java | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/src/main/java/gyro/azure/dns/DnsZoneResource.java b/src/main/java/gyro/azure/dns/DnsZoneResource.java index def19aed..89c44c2f 100644 --- a/src/main/java/gyro/azure/dns/DnsZoneResource.java +++ b/src/main/java/gyro/azure/dns/DnsZoneResource.java @@ -18,6 +18,8 @@ import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.dns.models.DnsZone; +import com.azure.resourcemanager.dns.models.NsRecordSet; +import com.azure.resourcemanager.resources.fluentcore.arm.models.HasName; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.azure.resources.ResourceGroupResource; @@ -30,9 +32,12 @@ import gyro.core.scope.State; import gyro.core.validation.Required; +import java.util.ArrayList; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Set; +import java.util.stream.Collectors; /** * Creates a DNS Zone. @@ -58,6 +63,9 @@ public class DnsZoneResource extends AzureResource implements Copyable private ResourceGroupResource resourceGroup; private Map tags; + private List nsRecords; + private Map> nameServers; + /** * The ID of the Dns Zone. */ @@ -111,12 +119,51 @@ public void setTags(Map tags) { this.tags = tags; } + /** + * List of ns record names present in the Dns Zone. + */ + @Output + public List getNsRecords() { + if (nsRecords == null) { + nsRecords = new ArrayList<>(); + } + + return nsRecords; + } + + public void setNsRecords(List nsRecords) { + this.nsRecords = nsRecords; + } + + /** + * A map of ns record names and corresponding name servers present in the Dns Zone. + */ + @Output + public Map> getNameServers() { + if (nameServers == null) { + nameServers = new HashMap<>(); + } + + return nameServers; + } + + public void setNameServers(Map> nameServers) { + this.nameServers = nameServers; + } + @Override public void copyFrom(DnsZone dnsZone) { setId(dnsZone.id()); setName(dnsZone.name()); setResourceGroup(findById(ResourceGroupResource.class, dnsZone.resourceGroupName())); setTags(dnsZone.tags()); + + setNsRecords(dnsZone.nsRecordSets().list().stream() + .map(HasName::name) + .collect(Collectors.toList())); + + setNameServers(dnsZone.nsRecordSets().list().stream() + .collect(Collectors.toMap(HasName::name, NsRecordSet::nameServers))); } @Override From d9f44c3e16f38bc87e54a7dfa882dd8bb32243b3 Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Mon, 28 Mar 2022 14:51:35 -0400 Subject: [PATCH 15/43] Update core ref update gyro core to release 1.1.2 Add updated reference to azure resource manager, container service and key vault certs --- build.gradle | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index 578d063c..d9b7a568 100644 --- a/build.gradle +++ b/build.gradle @@ -62,7 +62,7 @@ configurations { def azureSdkVersion = '1.41.2' dependencies { - api 'gyro:gyro-core:0.99.5' + (releaseBuild ? '' : '-SNAPSHOT') + api 'gyro:gyro-core:1.1.2' implementation 'com.psddev:dari-util:3.3.607-xe0f27a' implementation 'com.google.guava:guava:23.0' @@ -76,7 +76,9 @@ dependencies { implementation 'com.github.seancfoley:ipaddress:5.0.2' implementation 'org.reflections:reflections:0.9.10' - implementation 'com.azure.resourcemanager:azure-resourcemanager:2.11.0' + implementation 'com.azure.resourcemanager:azure-resourcemanager:2.13.0' + implementation 'com.azure.resourcemanager:azure-resourcemanager-containerservice:2.12.1' + implementation 'com.azure:azure-security-keyvault-certificates:4.3.0-beta.5' implementation 'com.azure:azure-identity:1.4.3' implementation 'com.azure:azure-core-http-okhttp:1.7.8' runtimeOnly 'com.nimbusds:oauth2-oidc-sdk:9.22.1' From 04e66d45e7e82fba66046b680e6f9e873fdf956f Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Mon, 4 Apr 2022 08:15:50 -0700 Subject: [PATCH 16/43] Add application resource --- examples/accessmanagement/application.gyro | 4 + .../accessmanagement/ApplicationFinder.java | 79 ++++++ .../accessmanagement/ApplicationResource.java | 261 ++++++++++++++++++ 3 files changed, 344 insertions(+) create mode 100644 examples/accessmanagement/application.gyro create mode 100644 src/main/java/gyro/azure/accessmanagement/ApplicationFinder.java create mode 100644 src/main/java/gyro/azure/accessmanagement/ApplicationResource.java diff --git a/examples/accessmanagement/application.gyro b/examples/accessmanagement/application.gyro new file mode 100644 index 00000000..c174ebf6 --- /dev/null +++ b/examples/accessmanagement/application.gyro @@ -0,0 +1,4 @@ +azure::application application-example + name: "application-example" + account-type: "AzureADMyOrg" +end diff --git a/src/main/java/gyro/azure/accessmanagement/ApplicationFinder.java b/src/main/java/gyro/azure/accessmanagement/ApplicationFinder.java new file mode 100644 index 00000000..6eef2a05 --- /dev/null +++ b/src/main/java/gyro/azure/accessmanagement/ApplicationFinder.java @@ -0,0 +1,79 @@ +/* + * Copyright 2022, Brightspot, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package gyro.azure.accessmanagement; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.authorization.models.ActiveDirectoryApplication; +import gyro.azure.AzureResourceManagerFinder; +import gyro.core.Type; + +/** + * Query application. + * + * Example + * ------- + * + * .. code-block:: gyro + * + * application: $(external-query azure::application {}) + */ +@Type("application") +public class ApplicationFinder extends AzureResourceManagerFinder { + + private String id; + + /** + * The id of the application. + */ + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + @Override + protected List findAllAzure(AzureResourceManager client) { + return client.accessManagement() + .activeDirectoryApplications() + .list().stream() + .collect(Collectors.toList()); + } + + @Override + protected List findAzure( + AzureResourceManager client, Map filters) { + + List applications = new ArrayList<>(); + + ActiveDirectoryApplication application = client.accessManagement() + .activeDirectoryApplications() + .getById(filters.get("id")); + + if (application != null) { + applications.add(application); + } + + return applications; + } +} diff --git a/src/main/java/gyro/azure/accessmanagement/ApplicationResource.java b/src/main/java/gyro/azure/accessmanagement/ApplicationResource.java new file mode 100644 index 00000000..7f695e76 --- /dev/null +++ b/src/main/java/gyro/azure/accessmanagement/ApplicationResource.java @@ -0,0 +1,261 @@ +/* + * Copyright 2022, Brightspot, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package gyro.azure.accessmanagement; + +import java.util.HashSet; +import java.util.Set; + +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.authorization.models.ActiveDirectoryApplication; +import gyro.azure.AzureResource; +import gyro.azure.Copyable; +import gyro.core.GyroUI; +import gyro.core.Type; +import gyro.core.resource.Id; +import gyro.core.resource.Output; +import gyro.core.resource.Resource; +import gyro.core.resource.Updatable; +import gyro.core.scope.State; +import gyro.core.validation.Required; +import gyro.core.validation.ValidStrings; +import org.apache.commons.lang3.StringUtils; + +/** + * Creates an application. + * + * Example + * ------- + * + * .. code-block:: gyro + * + * azure::application application-example + * name: "application-example" + * account-type: "AzureADMyOrg" + * end + * + * end + */ +@Type("application") +public class ApplicationResource extends AzureResource implements Copyable { + + private String name; + private String accountType; + private Set identifierUris; + private Set replyUrls; + private String signOnUrl; + + private String applicationId; + private String id; + + /** + * The name of the application. + */ + @Required + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Required + @Updatable + @ValidStrings({"AzureADMyOrg", "AzureADMultipleOrgs", "AzureADandPersonalMicrosoftAccount", "PersonalMicrosoftAccount"}) + public String getAccountType() { + return accountType; + } + + public void setAccountType(String accountType) { + this.accountType = accountType; + } + + /** + * A set of identifier uri's for the application. + */ + @Updatable + public Set getIdentifierUris() { + if (identifierUris == null) { + identifierUris = new HashSet<>(); + } + + return identifierUris; + } + + public void setIdentifierUris(Set identifierUris) { + this.identifierUris = identifierUris; + } + + /** + * A set of reply uri's for the application. + */ + @Updatable + public Set getReplyUrls() { + if (replyUrls == null) { + replyUrls = new HashSet<>(); + } + + return replyUrls; + } + + public void setReplyUrls(Set replyUrls) { + this.replyUrls = replyUrls; + } + + /** + * The sign on url for the application. + */ + @Updatable + public String getSignOnUrl() { + return signOnUrl; + } + + public void setSignOnUrl(String signOnUrl) { + this.signOnUrl = signOnUrl; + } + + /** + * The application id of the application. + */ + @Id + @Output + public String getApplicationId() { + return applicationId; + } + + public void setApplicationId(String applicationId) { + this.applicationId = applicationId; + } + + /** + * The id of the application. + */ + @Output + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + @Override + public void copyFrom(ActiveDirectoryApplication model) { + setName(model.name()); + setApplicationId(model.applicationId()); + setId(model.id()); + + setAccountType(model.accountType().toString()); + setIdentifierUris(model.identifierUris()); + setReplyUrls(model.replyUrls()); + setSignOnUrl(model.signOnUrl() != null ? model.signOnUrl().toString() : null); + } + + @Override + public boolean refresh() { + AzureResourceManager client = createResourceManagerClient(); + + ActiveDirectoryApplication application = client.accessManagement() + .activeDirectoryApplications() + .getById(getId()); + + if (application == null) { + return false; + } + + copyFrom(application); + + return true; + } + + @Override + public void create(GyroUI ui, State state) throws Exception { + AzureResourceManager client = createResourceManagerClient(); + + ActiveDirectoryApplication.DefinitionStages.WithCreate withCreate = client.accessManagement() + .activeDirectoryApplications() + .define(getName()) + .withAccountType(getAccountType()); + + for (String uri : getIdentifierUris()) { + withCreate = withCreate.withIdentifierUrl(uri); + } + + for (String uri : getReplyUrls()) { + withCreate = withCreate.withReplyUrl(uri); + } + + if (!StringUtils.isBlank(getSignOnUrl())) { + withCreate = withCreate.withSignOnUrl(getSignOnUrl()); + } + + ActiveDirectoryApplication application = withCreate.create(); + + copyFrom(application); + } + + @Override + public void update( + GyroUI ui, State state, Resource current, Set changedFieldNames) throws Exception { + AzureResourceManager client = createResourceManagerClient(); + + ActiveDirectoryApplication application = client.accessManagement() + .activeDirectoryApplications() + .getById(getId()); + + ActiveDirectoryApplication.Update update = application.update(); + + ApplicationResource currentApp = (ApplicationResource) current; + + if (changedFieldNames.contains("account-type")) { + update = update.withAccountType(getAccountType()); + } + + if (changedFieldNames.contains("identifier-uris")) { + for (String uri : currentApp.getIdentifierUris()) { + update = update.withoutIdentifierUrl(uri); + } + + for (String uri : getIdentifierUris()) { + update = update.withIdentifierUrl(uri); + } + } + + if (changedFieldNames.contains("reply-urls")) { + for (String uri : currentApp.getReplyUrls()) { + update = update.withoutReplyUrl(uri); + } + + for (String uri : getReplyUrls()) { + update = update.withReplyUrl(uri); + } + } + + if (changedFieldNames.contains("sign-on-url")) { + update = update.withSignOnUrl(getSignOnUrl()); + } + + update.apply(); + } + + @Override + public void delete(GyroUI ui, State state) throws Exception { + AzureResourceManager client = createResourceManagerClient(); + + client.accessManagement().activeDirectoryApplications().deleteById(getId()); + } +} From 3dc17fd4375c8f87f88b1396c2f7fb8c9b1277e8 Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Mon, 4 Apr 2022 08:16:05 -0700 Subject: [PATCH 17/43] Add service principal resource --- .../accessmanagement/serviceprincipal.gyro | 9 ++ .../ServicePrincipalFinder.java | 79 ++++++++++ .../ServicePrincipalResource.java | 138 ++++++++++++++++++ 3 files changed, 226 insertions(+) create mode 100644 examples/accessmanagement/serviceprincipal.gyro create mode 100644 src/main/java/gyro/azure/accessmanagement/ServicePrincipalFinder.java create mode 100644 src/main/java/gyro/azure/accessmanagement/ServicePrincipalResource.java diff --git a/examples/accessmanagement/serviceprincipal.gyro b/examples/accessmanagement/serviceprincipal.gyro new file mode 100644 index 00000000..e8ebff0d --- /dev/null +++ b/examples/accessmanagement/serviceprincipal.gyro @@ -0,0 +1,9 @@ +azure::application application-service-principal-example + name: "application-service-principal-example" + account-type: "AzureADMyOrg" +end + +azure::service-principal service-principal-example + name: "application-service-principal-example" + application: $(azure::application application-example) +end diff --git a/src/main/java/gyro/azure/accessmanagement/ServicePrincipalFinder.java b/src/main/java/gyro/azure/accessmanagement/ServicePrincipalFinder.java new file mode 100644 index 00000000..b261cbe1 --- /dev/null +++ b/src/main/java/gyro/azure/accessmanagement/ServicePrincipalFinder.java @@ -0,0 +1,79 @@ +/* + * Copyright 2022, Brightspot, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package gyro.azure.accessmanagement; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.authorization.models.ServicePrincipal; +import gyro.azure.AzureResourceManagerFinder; +import gyro.core.Type; + +/** + * Query service principal. + * + * Example + * ------- + * + * .. code-block:: gyro + * + * service-principal: $(external-query azure::service-principal {}) + */ +@Type("service-principal") +public class ServicePrincipalFinder extends AzureResourceManagerFinder { + + private String id; + + /** + * The id of the service principal. + */ + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + @Override + protected List findAllAzure(AzureResourceManager client) { + return client.accessManagement() + .servicePrincipals() + .list() + .stream() + .collect(Collectors.toList()); + } + + @Override + protected List findAzure( + AzureResourceManager client, Map filters) { + + List servicePrincipals = new ArrayList<>(); + ServicePrincipal servicePrincipal = client.accessManagement() + .servicePrincipals() + .getById(filters.get("id")); + + if (servicePrincipal != null) { + servicePrincipals.add(servicePrincipal); + } + + return servicePrincipals; + } +} diff --git a/src/main/java/gyro/azure/accessmanagement/ServicePrincipalResource.java b/src/main/java/gyro/azure/accessmanagement/ServicePrincipalResource.java new file mode 100644 index 00000000..2a3227f5 --- /dev/null +++ b/src/main/java/gyro/azure/accessmanagement/ServicePrincipalResource.java @@ -0,0 +1,138 @@ +/* + * Copyright 2022, Brightspot, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package gyro.azure.accessmanagement; + +import java.util.Set; + +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.authorization.models.ServicePrincipal; +import gyro.azure.AzureResource; +import gyro.azure.Copyable; +import gyro.core.GyroUI; +import gyro.core.Type; +import gyro.core.resource.Id; +import gyro.core.resource.Output; +import gyro.core.resource.Resource; +import gyro.core.scope.State; +import gyro.core.validation.Required; + +/** + * Creates a service principal. + * + * Example + * ------- + * + * .. code-block:: gyro + * + * azure::service-principal service-principal-example + * name: "application-service-principal-example" + * application: $(azure::application application-example) + * end + * + */ +@Type("service-principal") +public class ServicePrincipalResource extends AzureResource implements Copyable { + + private String name; + private ApplicationResource application; + + private String id; + + /** + * The name of the service principal. + */ + @Required + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + /** + * The application the service principal is going to be created for. + */ + @Required + public ApplicationResource getApplication() { + return application; + } + + public void setApplication(ApplicationResource application) { + this.application = application; + } + + /** + * The id of the service principal. + */ + @Id + @Output + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + @Override + public void copyFrom(ServicePrincipal model) { + setName(model.name()); + setApplication(findById(ApplicationResource.class, model.applicationId())); + setId(model.id()); + } + + @Override + public boolean refresh() { + AzureResourceManager client = createResourceManagerClient(); + + ServicePrincipal servicePrincipal = client.accessManagement().servicePrincipals().getByName(getName()); + + if (servicePrincipal == null) { + return false; + } + + copyFrom(servicePrincipal); + + return true; + } + + @Override + public void create(GyroUI ui, State state) throws Exception { + AzureResourceManager client = createResourceManagerClient(); + + ServicePrincipal servicePrincipal = client.accessManagement().servicePrincipals() + .define(getName()) + .withExistingApplication(getApplication().getApplicationId()) + .create(); + + copyFrom(servicePrincipal); + } + + @Override + public void update( + GyroUI ui, State state, Resource current, Set changedFieldNames) throws Exception { + + } + + @Override + public void delete(GyroUI ui, State state) throws Exception { + AzureResourceManager client = createResourceManagerClient(); + + client.accessManagement().servicePrincipals().deleteById(getId()); + } +} From b65f253047703823b67cca935079dca8839e49b3 Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Mon, 4 Apr 2022 08:16:28 -0700 Subject: [PATCH 18/43] Refactor role assignment resource --- .../RoleAssignmentResource.java | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/main/java/gyro/azure/accessmanagement/RoleAssignmentResource.java b/src/main/java/gyro/azure/accessmanagement/RoleAssignmentResource.java index d889eee4..e3fb7c3d 100644 --- a/src/main/java/gyro/azure/accessmanagement/RoleAssignmentResource.java +++ b/src/main/java/gyro/azure/accessmanagement/RoleAssignmentResource.java @@ -16,11 +16,11 @@ package gyro.azure.accessmanagement; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.graphrbac.ActiveDirectoryGroup; -import com.microsoft.azure.management.graphrbac.ActiveDirectoryUser; -import com.microsoft.azure.management.graphrbac.BuiltInRole; -import com.microsoft.azure.management.graphrbac.RoleAssignment; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.authorization.models.ActiveDirectoryGroup; +import com.azure.resourcemanager.authorization.models.ActiveDirectoryUser; +import com.azure.resourcemanager.authorization.models.BuiltInRole; +import com.azure.resourcemanager.authorization.models.RoleAssignment; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.core.GyroException; @@ -148,7 +148,7 @@ public void copyFrom(RoleAssignment roleAssignment) { setScope(roleAssignment.scope()); setId(roleAssignment.id()); - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); setRole(client.accessManagement().roleDefinitions().getById(roleAssignment.roleDefinitionId()).roleName()); ActiveDirectoryUser user = client.accessManagement().activeDirectoryUsers().getById(getPrincipalId()); @@ -165,7 +165,7 @@ public void copyFrom(RoleAssignment roleAssignment) { @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); RoleAssignment roleAssignment = client.accessManagement().roleAssignments().getByScope(getScope(), getName()); @@ -180,7 +180,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) throws Exception { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); if (Stream.of(getPrincipalId(), getUser(), getGroup()).filter(Objects::nonNull).count() > 1) { throw new GyroException("Only one of 'principal-id' or 'user' or 'group' is allowed."); @@ -220,7 +220,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) throws Exception { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); client.accessManagement().roleAssignments().deleteById(getId()); } From 01f7006532a3af417bdbc16086fffbe329db0eca Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Mon, 4 Apr 2022 08:56:38 -0700 Subject: [PATCH 19/43] Add license to container service --- .../containerservice/ApiServerAccessProfile.java | 16 ++++++++++++++++ .../containerservice/ClusterAddonProfile.java | 16 ++++++++++++++++ .../azure/containerservice/ClusterAgentPool.java | 16 ++++++++++++++++ .../ClusterLoadBalancerManagedOutboundIps.java | 16 ++++++++++++++++ .../ClusterLoadBalancerOutboundIpPrefixes.java | 16 ++++++++++++++++ .../ClusterLoadBalancerOutboundIps.java | 16 ++++++++++++++++ .../ClusterLoadBalancerProfile.java | 16 ++++++++++++++++ .../ClusterManagedOutboundIpProfile.java | 16 ++++++++++++++++ .../ClusterNatGatewayProfile.java | 16 ++++++++++++++++ .../ClusterPropertiesAutoScalerProfile.java | 16 ++++++++++++++++ .../KubernetesClusterFinder.java | 16 ++++++++++++++++ .../KubernetesClusterResource.java | 16 ++++++++++++++++ .../azure/containerservice/NetworkProfile.java | 16 ++++++++++++++++ 13 files changed, 208 insertions(+) diff --git a/src/main/java/gyro/azure/containerservice/ApiServerAccessProfile.java b/src/main/java/gyro/azure/containerservice/ApiServerAccessProfile.java index 1fa8149c..b4465893 100644 --- a/src/main/java/gyro/azure/containerservice/ApiServerAccessProfile.java +++ b/src/main/java/gyro/azure/containerservice/ApiServerAccessProfile.java @@ -1,3 +1,19 @@ +/* + * Copyright 2022, Brightspot, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package gyro.azure.containerservice; import java.util.ArrayList; diff --git a/src/main/java/gyro/azure/containerservice/ClusterAddonProfile.java b/src/main/java/gyro/azure/containerservice/ClusterAddonProfile.java index 36a81071..f10268a8 100644 --- a/src/main/java/gyro/azure/containerservice/ClusterAddonProfile.java +++ b/src/main/java/gyro/azure/containerservice/ClusterAddonProfile.java @@ -1,3 +1,19 @@ +/* + * Copyright 2022, Brightspot, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package gyro.azure.containerservice; import java.util.HashMap; diff --git a/src/main/java/gyro/azure/containerservice/ClusterAgentPool.java b/src/main/java/gyro/azure/containerservice/ClusterAgentPool.java index e4023709..1b8445a0 100644 --- a/src/main/java/gyro/azure/containerservice/ClusterAgentPool.java +++ b/src/main/java/gyro/azure/containerservice/ClusterAgentPool.java @@ -1,3 +1,19 @@ +/* + * Copyright 2022, Brightspot, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package gyro.azure.containerservice; import java.util.ArrayList; diff --git a/src/main/java/gyro/azure/containerservice/ClusterLoadBalancerManagedOutboundIps.java b/src/main/java/gyro/azure/containerservice/ClusterLoadBalancerManagedOutboundIps.java index f1e8a012..90324030 100644 --- a/src/main/java/gyro/azure/containerservice/ClusterLoadBalancerManagedOutboundIps.java +++ b/src/main/java/gyro/azure/containerservice/ClusterLoadBalancerManagedOutboundIps.java @@ -1,3 +1,19 @@ +/* + * Copyright 2022, Brightspot, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package gyro.azure.containerservice; import com.azure.resourcemanager.containerservice.models.ManagedClusterLoadBalancerProfileManagedOutboundIPs; diff --git a/src/main/java/gyro/azure/containerservice/ClusterLoadBalancerOutboundIpPrefixes.java b/src/main/java/gyro/azure/containerservice/ClusterLoadBalancerOutboundIpPrefixes.java index 01dd2cb8..5873d1cf 100644 --- a/src/main/java/gyro/azure/containerservice/ClusterLoadBalancerOutboundIpPrefixes.java +++ b/src/main/java/gyro/azure/containerservice/ClusterLoadBalancerOutboundIpPrefixes.java @@ -1,3 +1,19 @@ +/* + * Copyright 2022, Brightspot, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package gyro.azure.containerservice; import java.util.ArrayList; diff --git a/src/main/java/gyro/azure/containerservice/ClusterLoadBalancerOutboundIps.java b/src/main/java/gyro/azure/containerservice/ClusterLoadBalancerOutboundIps.java index 44628c85..2b99b7c0 100644 --- a/src/main/java/gyro/azure/containerservice/ClusterLoadBalancerOutboundIps.java +++ b/src/main/java/gyro/azure/containerservice/ClusterLoadBalancerOutboundIps.java @@ -1,3 +1,19 @@ +/* + * Copyright 2022, Brightspot, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package gyro.azure.containerservice; import java.util.ArrayList; diff --git a/src/main/java/gyro/azure/containerservice/ClusterLoadBalancerProfile.java b/src/main/java/gyro/azure/containerservice/ClusterLoadBalancerProfile.java index 97c7d281..f3c5fa8b 100644 --- a/src/main/java/gyro/azure/containerservice/ClusterLoadBalancerProfile.java +++ b/src/main/java/gyro/azure/containerservice/ClusterLoadBalancerProfile.java @@ -1,3 +1,19 @@ +/* + * Copyright 2022, Brightspot, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package gyro.azure.containerservice; import java.util.ArrayList; diff --git a/src/main/java/gyro/azure/containerservice/ClusterManagedOutboundIpProfile.java b/src/main/java/gyro/azure/containerservice/ClusterManagedOutboundIpProfile.java index 35bd77fe..3e1dbb2d 100644 --- a/src/main/java/gyro/azure/containerservice/ClusterManagedOutboundIpProfile.java +++ b/src/main/java/gyro/azure/containerservice/ClusterManagedOutboundIpProfile.java @@ -1,3 +1,19 @@ +/* + * Copyright 2022, Brightspot, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package gyro.azure.containerservice; import com.azure.resourcemanager.containerservice.models.ManagedClusterManagedOutboundIpProfile; diff --git a/src/main/java/gyro/azure/containerservice/ClusterNatGatewayProfile.java b/src/main/java/gyro/azure/containerservice/ClusterNatGatewayProfile.java index 165fd456..55536e69 100644 --- a/src/main/java/gyro/azure/containerservice/ClusterNatGatewayProfile.java +++ b/src/main/java/gyro/azure/containerservice/ClusterNatGatewayProfile.java @@ -1,3 +1,19 @@ +/* + * Copyright 2022, Brightspot, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package gyro.azure.containerservice; import java.util.ArrayList; diff --git a/src/main/java/gyro/azure/containerservice/ClusterPropertiesAutoScalerProfile.java b/src/main/java/gyro/azure/containerservice/ClusterPropertiesAutoScalerProfile.java index 18d2d695..02c833e2 100644 --- a/src/main/java/gyro/azure/containerservice/ClusterPropertiesAutoScalerProfile.java +++ b/src/main/java/gyro/azure/containerservice/ClusterPropertiesAutoScalerProfile.java @@ -1,3 +1,19 @@ +/* + * Copyright 2022, Brightspot, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package gyro.azure.containerservice; import com.azure.resourcemanager.containerservice.models.Expander; diff --git a/src/main/java/gyro/azure/containerservice/KubernetesClusterFinder.java b/src/main/java/gyro/azure/containerservice/KubernetesClusterFinder.java index 29109bce..ed3e75b8 100644 --- a/src/main/java/gyro/azure/containerservice/KubernetesClusterFinder.java +++ b/src/main/java/gyro/azure/containerservice/KubernetesClusterFinder.java @@ -1,3 +1,19 @@ +/* + * Copyright 2022, Brightspot, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package gyro.azure.containerservice; import java.util.ArrayList; diff --git a/src/main/java/gyro/azure/containerservice/KubernetesClusterResource.java b/src/main/java/gyro/azure/containerservice/KubernetesClusterResource.java index 8dfebd69..445a69c3 100644 --- a/src/main/java/gyro/azure/containerservice/KubernetesClusterResource.java +++ b/src/main/java/gyro/azure/containerservice/KubernetesClusterResource.java @@ -1,3 +1,19 @@ +/* + * Copyright 2022, Brightspot, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package gyro.azure.containerservice; import java.util.HashMap; diff --git a/src/main/java/gyro/azure/containerservice/NetworkProfile.java b/src/main/java/gyro/azure/containerservice/NetworkProfile.java index ebc067c3..56f157fb 100644 --- a/src/main/java/gyro/azure/containerservice/NetworkProfile.java +++ b/src/main/java/gyro/azure/containerservice/NetworkProfile.java @@ -1,3 +1,19 @@ +/* + * Copyright 2022, Brightspot, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package gyro.azure.containerservice; import com.azure.resourcemanager.containerservice.models.ContainerServiceNetworkProfile; From 802db377920da3fb28d7df4e5bd35181ff17c774 Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Tue, 5 Apr 2022 12:12:09 -0700 Subject: [PATCH 20/43] fix service principal example --- examples/accessmanagement/serviceprincipal.gyro | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/accessmanagement/serviceprincipal.gyro b/examples/accessmanagement/serviceprincipal.gyro index e8ebff0d..42780e58 100644 --- a/examples/accessmanagement/serviceprincipal.gyro +++ b/examples/accessmanagement/serviceprincipal.gyro @@ -5,5 +5,5 @@ end azure::service-principal service-principal-example name: "application-service-principal-example" - application: $(azure::application application-example) + application: $(azure::application application-service-principal-example) end From c62d8514560afa0a6cd910ea658b0a53da9dbf46 Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Tue, 5 Apr 2022 12:13:40 -0700 Subject: [PATCH 21/43] Add identity resource --- examples/accessmanagement/identity.gyro | 16 ++ .../accessmanagement/IdentityFinder.java | 76 ++++++ .../accessmanagement/IdentityResource.java | 230 ++++++++++++++++++ 3 files changed, 322 insertions(+) create mode 100644 examples/accessmanagement/identity.gyro create mode 100644 src/main/java/gyro/azure/accessmanagement/IdentityFinder.java create mode 100644 src/main/java/gyro/azure/accessmanagement/IdentityResource.java diff --git a/examples/accessmanagement/identity.gyro b/examples/accessmanagement/identity.gyro new file mode 100644 index 00000000..2af1edbd --- /dev/null +++ b/examples/accessmanagement/identity.gyro @@ -0,0 +1,16 @@ +azure::resource-group identity-example + name: "identity-example" + + tags: { + Name: "identity-example" + } +end + +azure::identity identity-example + name: "identity-example" + resource-group: $(azure::resource-group identity-example) + + tags: { + Name: "identity-example" + } +end diff --git a/src/main/java/gyro/azure/accessmanagement/IdentityFinder.java b/src/main/java/gyro/azure/accessmanagement/IdentityFinder.java new file mode 100644 index 00000000..3163dc95 --- /dev/null +++ b/src/main/java/gyro/azure/accessmanagement/IdentityFinder.java @@ -0,0 +1,76 @@ +/* + * Copyright 2022, Brightspot, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package gyro.azure.accessmanagement; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.msi.models.Identity; +import gyro.azure.AzureResourceManagerFinder; +import gyro.core.Type; + +/** + * Query identity. + * + * Example + * ------- + * + * .. code-block:: gyro + * + * identity: $(external-query azure::identity {}) + */ +@Type("identity") +public class IdentityFinder extends AzureResourceManagerFinder { + + private String id; + + /** + * The id of the identity. + */ + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + @Override + protected List findAllAzure(AzureResourceManager client) { + return client.identities() + .list() + .stream() + .collect(Collectors.toList()); + } + + @Override + protected List findAzure( + AzureResourceManager client, Map filters) { + List identities = new ArrayList<>(); + + Identity identity = client.identities().getById(filters.get("id")); + + if (identity != null) { + identities.add(identity); + } + + return identities; + } +} diff --git a/src/main/java/gyro/azure/accessmanagement/IdentityResource.java b/src/main/java/gyro/azure/accessmanagement/IdentityResource.java new file mode 100644 index 00000000..a5aded6e --- /dev/null +++ b/src/main/java/gyro/azure/accessmanagement/IdentityResource.java @@ -0,0 +1,230 @@ +/* + * Copyright 2022, Brightspot, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package gyro.azure.accessmanagement; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.msi.models.Identity; +import gyro.azure.AzureResource; +import gyro.azure.Copyable; +import gyro.azure.resources.ResourceGroupResource; +import gyro.core.GyroUI; +import gyro.core.Type; +import gyro.core.resource.Id; +import gyro.core.resource.Output; +import gyro.core.resource.Resource; +import gyro.core.resource.Updatable; +import gyro.core.scope.State; +import gyro.core.validation.Required; + +/** + * Creates an identity. + * + * Example + * ------- + * + * .. code-block:: gyro + * + * azure::identity identity-example + * name: "identity-example" + * resource-group: $(azure::resource-group identity-example) + * + * tags: { + * Name: "identity-example" + * } + * end + * + */ +@Type("identity") +public class IdentityResource extends AzureResource implements Copyable { + + private String name; + private ResourceGroupResource resourceGroup; + private Map tags; + + private String id; + private String tenantId; + private String clientId; + private String principalId; + + /** + * The name of the identity. + */ + @Required + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + /** + * The resource group associated with the identity. + */ + @Required + public ResourceGroupResource getResourceGroup() { + return resourceGroup; + } + + public void setResourceGroup(ResourceGroupResource resourceGroup) { + this.resourceGroup = resourceGroup; + } + + /** + * A set of tags for the identity. + */ + @Updatable + public Map getTags() { + if (tags == null) { + tags = new HashMap<>(); + } + + return tags; + } + + public void setTags(Map tags) { + this.tags = tags; + } + + /** + * The id of the identity. + */ + @Id + @Output + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + /** + * The associated tenant id of the identity. + */ + @Output + public String getTenantId() { + return tenantId; + } + + public void setTenantId(String tenantId) { + this.tenantId = tenantId; + } + + /** + * The client id of the identity. + */ + @Output + public String getClientId() { + return clientId; + } + + public void setClientId(String clientId) { + this.clientId = clientId; + } + + /** + * The principal id of the identity. + */ + @Output + public String getPrincipalId() { + return principalId; + } + + public void setPrincipalId(String principalId) { + this.principalId = principalId; + } + + @Override + public void copyFrom(Identity model) { + setName(model.name()); + setResourceGroup(findById(ResourceGroupResource.class, model.resourceGroupName())); + setTags(model.tags()); + setId(model.id()); + setClientId(model.clientId()); + setTenantId(model.tenantId()); + setPrincipalId(model.principalId()); + } + + @Override + public boolean refresh() { + AzureResourceManager client = createResourceManagerClient(); + + Identity identity = client.identities().getById(getId()); + + if (identity == null) { + return false; + } + + copyFrom(identity); + + return true; + } + + @Override + public void create(GyroUI ui, State state) throws Exception { + AzureResourceManager client = createResourceManagerClient(); + + Identity.DefinitionStages.WithCreate withCreate = client.identities() + .define(getName()) + .withRegion(getRegion()) + .withExistingResourceGroup(getResourceGroup().getName()); + + if (!getTags().isEmpty()) { + withCreate = withCreate.withTags(getTags()); + } + + Identity identity = withCreate.create(); + + copyFrom(identity); + } + + @Override + public void update( + GyroUI ui, State state, Resource current, Set changedFieldNames) throws Exception { + AzureResourceManager client = createResourceManagerClient(); + + IdentityResource currentResource = (IdentityResource) current; + + Identity identity = client.identities().getById(getId()); + + Identity.Update update = identity.update(); + + if (!currentResource.getTags().isEmpty()) { + for (String key : currentResource.getTags().keySet()) { + update = update.withoutTag(key); + } + } + + if (!getTags().isEmpty()) { + update.withTags(getTags()); + } + + update.apply(); + } + + @Override + public void delete(GyroUI ui, State state) throws Exception { + AzureResourceManager client = createResourceManagerClient(); + + client.identities().deleteById(getId()); + } +} From 169d1cd17b7a192dec790bd1bce55382e3fd97b2 Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Tue, 26 Apr 2022 09:28:17 -0400 Subject: [PATCH 22/43] Attach network profile on create of a cluster --- .../KubernetesClusterResource.java | 32 +++++++++++++++++++ .../containerservice/NetworkProfile.java | 2 +- 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/src/main/java/gyro/azure/containerservice/KubernetesClusterResource.java b/src/main/java/gyro/azure/containerservice/KubernetesClusterResource.java index 445a69c3..6e1bb718 100644 --- a/src/main/java/gyro/azure/containerservice/KubernetesClusterResource.java +++ b/src/main/java/gyro/azure/containerservice/KubernetesClusterResource.java @@ -32,10 +32,15 @@ import com.azure.resourcemanager.containerservice.models.KubernetesCluster; import com.azure.resourcemanager.containerservice.models.KubernetesClusterAgentPool; import com.azure.resourcemanager.containerservice.models.KubernetesClusters; +import com.azure.resourcemanager.containerservice.models.LoadBalancerSku; import com.azure.resourcemanager.containerservice.models.ManagedClusterAddonProfile; import com.azure.resourcemanager.containerservice.models.ManagedClusterApiServerAccessProfile; +import com.azure.resourcemanager.containerservice.models.NetworkMode; +import com.azure.resourcemanager.containerservice.models.NetworkPlugin; +import com.azure.resourcemanager.containerservice.models.NetworkPolicy; import com.azure.resourcemanager.containerservice.models.OSDiskType; import com.azure.resourcemanager.containerservice.models.OSType; +import com.azure.resourcemanager.containerservice.models.OutboundType; import com.azure.resourcemanager.containerservice.models.PublicNetworkAccess; import com.azure.resourcemanager.containerservice.models.ScaleSetEvictionPolicy; import com.azure.resourcemanager.containerservice.models.ScaleSetPriority; @@ -587,6 +592,33 @@ public void create(GyroUI ui, State state) throws Exception { } } + if (getNetworkProfile() != null) { + NetworkProfile network = getNetworkProfile(); + KubernetesCluster.DefinitionStages.NetworkProfileDefinitionStages.WithAttach withAttach = withCreate.defineNetworkProfile() + .withNetworkPlugin(NetworkPlugin.fromString(network.getNetworkPlugin())); + + if (!StringUtils.isBlank(network.getNetworkPolicy())) { + withAttach = withAttach.withNetworkPolicy(NetworkPolicy.fromString(network.getNetworkPolicy())); + } + + if (!StringUtils.isBlank(network.getPodCidr())) { + withAttach = withAttach.withPodCidr(network.getPodCidr()); + } + if (!StringUtils.isBlank(network.getDockerBridgeCidr())) { + withAttach = withAttach.withDockerBridgeCidr(network.getDockerBridgeCidr()); + } + + if (!StringUtils.isBlank(network.getServiceCidr())) { + withAttach = withAttach.withServiceCidr(network.getServiceCidr()); + } + + if (!StringUtils.isBlank(network.getLoadBalancerSku())) { + withAttach = withAttach.withLoadBalancerSku(LoadBalancerSku.fromString(network.getLoadBalancerSku())); + } + + withCreate = withAttach.attach(); + } + if (!getTags().isEmpty()) { withCreate = withCreate.withTags(getTags()); } diff --git a/src/main/java/gyro/azure/containerservice/NetworkProfile.java b/src/main/java/gyro/azure/containerservice/NetworkProfile.java index 56f157fb..eab6072d 100644 --- a/src/main/java/gyro/azure/containerservice/NetworkProfile.java +++ b/src/main/java/gyro/azure/containerservice/NetworkProfile.java @@ -70,7 +70,7 @@ public void setDockerBridgeCidr(String dockerBridgeCidr) { /** * The network plugin for the network profile. */ - @Updatable + @Required @ValidStrings({"azure", "kubenet"}) public String getNetworkPlugin() { return networkPlugin; From b18567f0dfd43995a666059633559fce3c37069d Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Tue, 26 Apr 2022 10:04:56 -0400 Subject: [PATCH 23/43] Remove setting enable-private-cluster The api does not have enough info on this --- .../azure/containerservice/KubernetesClusterResource.java | 8 -------- 1 file changed, 8 deletions(-) diff --git a/src/main/java/gyro/azure/containerservice/KubernetesClusterResource.java b/src/main/java/gyro/azure/containerservice/KubernetesClusterResource.java index 6e1bb718..55dd42b5 100644 --- a/src/main/java/gyro/azure/containerservice/KubernetesClusterResource.java +++ b/src/main/java/gyro/azure/containerservice/KubernetesClusterResource.java @@ -453,8 +453,6 @@ public void copyFrom(KubernetesCluster cluster) { setId(cluster.id()); setResourceGroup(findById(ResourceGroupResource.class, cluster.resourceGroupName())); setTags(cluster.tags()); - setEnablePrivateCluster(cluster.innerModel().publicNetworkAccess() == null - || cluster.innerModel().publicNetworkAccess().equals(PublicNetworkAccess.DISABLED)); Set addonProfiles = new HashSet<>(); try { @@ -501,10 +499,6 @@ public void copyFrom(KubernetesCluster cluster) { if (cluster.innerModel().apiServerAccessProfile() != null) { apiServerAccessProfile = newSubresource(ApiServerAccessProfile.class); apiServerAccessProfile.copyFrom(cluster.innerModel().apiServerAccessProfile()); - - if (apiServerAccessProfile.getEnablePrivateCluster() != null) { - setEnablePrivateCluster(apiServerAccessProfile.getEnablePrivateCluster()); - } } setApiServerAccessProfile(apiServerAccessProfile); } @@ -518,10 +512,8 @@ public boolean refresh() { .filter(o -> o.resourceGroupName().equals(getResourceGroup().getName())) .findFirst().orElse(null); - boolean privateCluster = getEnablePrivateCluster(); if (cluster != null) { copyFrom(cluster); - setEnablePrivateCluster(privateCluster); return true; } From b4814dd19c46ef02a26b2c92240711f742fe8736 Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Wed, 27 Apr 2022 20:27:37 -0400 Subject: [PATCH 24/43] Fix node pool refresh issue --- .../azure/containerservice/KubernetesClusterResource.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/gyro/azure/containerservice/KubernetesClusterResource.java b/src/main/java/gyro/azure/containerservice/KubernetesClusterResource.java index 55dd42b5..a25da395 100644 --- a/src/main/java/gyro/azure/containerservice/KubernetesClusterResource.java +++ b/src/main/java/gyro/azure/containerservice/KubernetesClusterResource.java @@ -553,7 +553,7 @@ public void create(GyroUI ui, State state) throws Exception { WithAttach withAttach = createStage .withVirtualMachineSize(ContainerServiceVMSizeTypes.fromString(agentPool.getSize())) - .withAgentPoolVirtualMachineCount(agentPool.getCount()) + .withAgentPoolVirtualMachineCount(agentPool.getMinimumNodeSize()) .withTags(agentPool.getTags()) .withAgentPoolMode(AgentPoolMode.fromString(agentPool.getMode())) @@ -762,7 +762,7 @@ public void update( for (ClusterAgentPool agentPool : addAgentPool) { WithAttach withAttach = update.defineAgentPool(agentPool.getName()) .withVirtualMachineSize(ContainerServiceVMSizeTypes.fromString(agentPool.getSize())) - .withAgentPoolVirtualMachineCount(agentPool.getCount()) + .withAgentPoolVirtualMachineCount(agentPool.getMinimumNodeSize()) .withTags(agentPool.getTags()) .withAgentPoolMode(AgentPoolMode.fromString(agentPool.getMode())) From 9c70c25903d6315a68f813709b601837861bf23f Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Sun, 1 May 2022 14:56:26 -0400 Subject: [PATCH 25/43] identity refactor --- examples/accessmanagement/identity.gyro | 16 -- .../accessmanagement/IdentityFinder.java | 76 ------ .../accessmanagement/IdentityResource.java | 230 ------------------ .../gyro/azure/identity/IdentityFinder.java | 15 +- .../gyro/azure/identity/IdentityResource.java | 14 +- 5 files changed, 15 insertions(+), 336 deletions(-) delete mode 100644 examples/accessmanagement/identity.gyro delete mode 100644 src/main/java/gyro/azure/accessmanagement/IdentityFinder.java delete mode 100644 src/main/java/gyro/azure/accessmanagement/IdentityResource.java diff --git a/examples/accessmanagement/identity.gyro b/examples/accessmanagement/identity.gyro deleted file mode 100644 index 2af1edbd..00000000 --- a/examples/accessmanagement/identity.gyro +++ /dev/null @@ -1,16 +0,0 @@ -azure::resource-group identity-example - name: "identity-example" - - tags: { - Name: "identity-example" - } -end - -azure::identity identity-example - name: "identity-example" - resource-group: $(azure::resource-group identity-example) - - tags: { - Name: "identity-example" - } -end diff --git a/src/main/java/gyro/azure/accessmanagement/IdentityFinder.java b/src/main/java/gyro/azure/accessmanagement/IdentityFinder.java deleted file mode 100644 index 3163dc95..00000000 --- a/src/main/java/gyro/azure/accessmanagement/IdentityFinder.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright 2022, Brightspot, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package gyro.azure.accessmanagement; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import com.azure.resourcemanager.AzureResourceManager; -import com.azure.resourcemanager.msi.models.Identity; -import gyro.azure.AzureResourceManagerFinder; -import gyro.core.Type; - -/** - * Query identity. - * - * Example - * ------- - * - * .. code-block:: gyro - * - * identity: $(external-query azure::identity {}) - */ -@Type("identity") -public class IdentityFinder extends AzureResourceManagerFinder { - - private String id; - - /** - * The id of the identity. - */ - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - @Override - protected List findAllAzure(AzureResourceManager client) { - return client.identities() - .list() - .stream() - .collect(Collectors.toList()); - } - - @Override - protected List findAzure( - AzureResourceManager client, Map filters) { - List identities = new ArrayList<>(); - - Identity identity = client.identities().getById(filters.get("id")); - - if (identity != null) { - identities.add(identity); - } - - return identities; - } -} diff --git a/src/main/java/gyro/azure/accessmanagement/IdentityResource.java b/src/main/java/gyro/azure/accessmanagement/IdentityResource.java deleted file mode 100644 index a5aded6e..00000000 --- a/src/main/java/gyro/azure/accessmanagement/IdentityResource.java +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Copyright 2022, Brightspot, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package gyro.azure.accessmanagement; - -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -import com.azure.resourcemanager.AzureResourceManager; -import com.azure.resourcemanager.msi.models.Identity; -import gyro.azure.AzureResource; -import gyro.azure.Copyable; -import gyro.azure.resources.ResourceGroupResource; -import gyro.core.GyroUI; -import gyro.core.Type; -import gyro.core.resource.Id; -import gyro.core.resource.Output; -import gyro.core.resource.Resource; -import gyro.core.resource.Updatable; -import gyro.core.scope.State; -import gyro.core.validation.Required; - -/** - * Creates an identity. - * - * Example - * ------- - * - * .. code-block:: gyro - * - * azure::identity identity-example - * name: "identity-example" - * resource-group: $(azure::resource-group identity-example) - * - * tags: { - * Name: "identity-example" - * } - * end - * - */ -@Type("identity") -public class IdentityResource extends AzureResource implements Copyable { - - private String name; - private ResourceGroupResource resourceGroup; - private Map tags; - - private String id; - private String tenantId; - private String clientId; - private String principalId; - - /** - * The name of the identity. - */ - @Required - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - /** - * The resource group associated with the identity. - */ - @Required - public ResourceGroupResource getResourceGroup() { - return resourceGroup; - } - - public void setResourceGroup(ResourceGroupResource resourceGroup) { - this.resourceGroup = resourceGroup; - } - - /** - * A set of tags for the identity. - */ - @Updatable - public Map getTags() { - if (tags == null) { - tags = new HashMap<>(); - } - - return tags; - } - - public void setTags(Map tags) { - this.tags = tags; - } - - /** - * The id of the identity. - */ - @Id - @Output - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - /** - * The associated tenant id of the identity. - */ - @Output - public String getTenantId() { - return tenantId; - } - - public void setTenantId(String tenantId) { - this.tenantId = tenantId; - } - - /** - * The client id of the identity. - */ - @Output - public String getClientId() { - return clientId; - } - - public void setClientId(String clientId) { - this.clientId = clientId; - } - - /** - * The principal id of the identity. - */ - @Output - public String getPrincipalId() { - return principalId; - } - - public void setPrincipalId(String principalId) { - this.principalId = principalId; - } - - @Override - public void copyFrom(Identity model) { - setName(model.name()); - setResourceGroup(findById(ResourceGroupResource.class, model.resourceGroupName())); - setTags(model.tags()); - setId(model.id()); - setClientId(model.clientId()); - setTenantId(model.tenantId()); - setPrincipalId(model.principalId()); - } - - @Override - public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); - - Identity identity = client.identities().getById(getId()); - - if (identity == null) { - return false; - } - - copyFrom(identity); - - return true; - } - - @Override - public void create(GyroUI ui, State state) throws Exception { - AzureResourceManager client = createResourceManagerClient(); - - Identity.DefinitionStages.WithCreate withCreate = client.identities() - .define(getName()) - .withRegion(getRegion()) - .withExistingResourceGroup(getResourceGroup().getName()); - - if (!getTags().isEmpty()) { - withCreate = withCreate.withTags(getTags()); - } - - Identity identity = withCreate.create(); - - copyFrom(identity); - } - - @Override - public void update( - GyroUI ui, State state, Resource current, Set changedFieldNames) throws Exception { - AzureResourceManager client = createResourceManagerClient(); - - IdentityResource currentResource = (IdentityResource) current; - - Identity identity = client.identities().getById(getId()); - - Identity.Update update = identity.update(); - - if (!currentResource.getTags().isEmpty()) { - for (String key : currentResource.getTags().keySet()) { - update = update.withoutTag(key); - } - } - - if (!getTags().isEmpty()) { - update.withTags(getTags()); - } - - update.apply(); - } - - @Override - public void delete(GyroUI ui, State state) throws Exception { - AzureResourceManager client = createResourceManagerClient(); - - client.identities().deleteById(getId()); - } -} diff --git a/src/main/java/gyro/azure/identity/IdentityFinder.java b/src/main/java/gyro/azure/identity/IdentityFinder.java index cc4aaa09..0f04e0b9 100644 --- a/src/main/java/gyro/azure/identity/IdentityFinder.java +++ b/src/main/java/gyro/azure/identity/IdentityFinder.java @@ -16,14 +16,15 @@ package gyro.azure.identity; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.msi.Identity; -import gyro.azure.AzureFinder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.msi.models.Identity; +import gyro.azure.AzureResourceManagerFinder; import gyro.core.Type; import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; /** * Query identity. @@ -36,7 +37,7 @@ * identity: $(external-query azure::identity {}) */ @Type("identity") -public class IdentityFinder extends AzureFinder { +public class IdentityFinder extends AzureResourceManagerFinder { private String id; /** @@ -51,12 +52,12 @@ public void setId(String id) { } @Override - protected List findAllAzure(Azure client) { - return client.identities().list(); + protected List findAllAzure(AzureResourceManager client) { + return client.identities().list().stream().collect(Collectors.toList()); } @Override - protected List findAzure(Azure client, Map filters) { + protected List findAzure(AzureResourceManager client, Map filters) { Identity identity = client.identities().getById(filters.get("id")); if (identity == null) { diff --git a/src/main/java/gyro/azure/identity/IdentityResource.java b/src/main/java/gyro/azure/identity/IdentityResource.java index 691ae20e..dad97b47 100644 --- a/src/main/java/gyro/azure/identity/IdentityResource.java +++ b/src/main/java/gyro/azure/identity/IdentityResource.java @@ -16,9 +16,9 @@ package gyro.azure.identity; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.msi.Identity; -import com.microsoft.azure.management.resources.fluentcore.arm.Region; +import com.azure.core.management.Region; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.msi.models.Identity; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.azure.resources.ResourceGroupResource; @@ -164,7 +164,7 @@ public void copyFrom(Identity identity) { @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); Identity identity = client.identities().getById(getId()); @@ -179,7 +179,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) throws Exception { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); Identity identity = client.identities().define(getName()) .withRegion(Region.fromName(getRegion())) @@ -192,7 +192,7 @@ public void create(GyroUI ui, State state) throws Exception { @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) throws Exception { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); Identity.Update update = client.identities().getById(getId()).update(); IdentityResource oldResource = (IdentityResource) current; @@ -212,7 +212,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) throws Exception { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); client.identities().deleteById(getId()); } From a274280f451187fd45f444aee5efa511dc3038cc Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Sun, 1 May 2022 14:56:50 -0400 Subject: [PATCH 26/43] update azure jar ref --- build.gradle | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/build.gradle b/build.gradle index d9b7a568..06f4469c 100644 --- a/build.gradle +++ b/build.gradle @@ -76,12 +76,11 @@ dependencies { implementation 'com.github.seancfoley:ipaddress:5.0.2' implementation 'org.reflections:reflections:0.9.10' - implementation 'com.azure.resourcemanager:azure-resourcemanager:2.13.0' - implementation 'com.azure.resourcemanager:azure-resourcemanager-containerservice:2.12.1' - implementation 'com.azure:azure-security-keyvault-certificates:4.3.0-beta.5' - implementation 'com.azure:azure-identity:1.4.3' - implementation 'com.azure:azure-core-http-okhttp:1.7.8' - runtimeOnly 'com.nimbusds:oauth2-oidc-sdk:9.22.1' + implementation 'com.azure.resourcemanager:azure-resourcemanager:2.14.0' + implementation 'com.azure:azure-security-keyvault-certificates:4.3.1' + implementation 'com.azure:azure-identity:1.5.0' + implementation 'com.azure:azure-core-http-okhttp:1.8.0' + runtimeOnly 'com.nimbusds:oauth2-oidc-sdk:9.34' gyroDoclet 'gyro:gyro-doclet:1.0.0' } From 50c6a5f38c9a0bdc9b1e94c485a77a463516a7dc Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Sun, 1 May 2022 14:58:23 -0400 Subject: [PATCH 27/43] remove count as required field from agentpool --- src/main/java/gyro/azure/containerservice/ClusterAgentPool.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/gyro/azure/containerservice/ClusterAgentPool.java b/src/main/java/gyro/azure/containerservice/ClusterAgentPool.java index 1b8445a0..155ab1d1 100644 --- a/src/main/java/gyro/azure/containerservice/ClusterAgentPool.java +++ b/src/main/java/gyro/azure/containerservice/ClusterAgentPool.java @@ -88,7 +88,6 @@ public void setSize(String size) { /** * The node count of the agent pool. */ - @Required @Updatable public Integer getCount() { return count; From 1a4d3f4e6459e2ea385a196185af747d44041126 Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Sun, 1 May 2022 14:58:46 -0400 Subject: [PATCH 28/43] Fix kubernetes cluster example --- examples/containerservice/kubernetes-cluster.gyro | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/containerservice/kubernetes-cluster.gyro b/examples/containerservice/kubernetes-cluster.gyro index 0ff39708..0c7dacfa 100644 --- a/examples/containerservice/kubernetes-cluster.gyro +++ b/examples/containerservice/kubernetes-cluster.gyro @@ -86,8 +86,9 @@ azure::kubernetes-cluster kubernetes-cluster-example dns-service-ip: "10.0.0.10" docker-bridge-cidr: "172.17.0.1/16" service-cidr: "10.0.0.0/16" - load-balancer-sku: "standard" + load-balancer-sku: "Standard" outbound-type: "loadBalancer" + network-plugin: "azure" load-balancer-profile outbound-ips @@ -101,5 +102,4 @@ azure::kubernetes-cluster kubernetes-cluster-example Name: "kubernetes-cluster-example" } - end From 1bcdac34108e9341800397b696bd042b03373b2f Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Tue, 24 May 2022 18:01:45 -0400 Subject: [PATCH 29/43] Initial sql refactor --- .../gyro/azure/sql/SqlDatabaseFinder.java | 26 +- .../gyro/azure/sql/SqlDatabaseResource.java | 206 ++++++++++------ .../gyro/azure/sql/SqlElasticPoolFinder.java | 26 +- .../azure/sql/SqlElasticPoolResource.java | 230 ++++++++++++------ .../azure/sql/SqlFailoverGroupFinder.java | 26 +- .../azure/sql/SqlFailoverGroupResource.java | 48 ++-- .../gyro/azure/sql/SqlFirewallRuleFinder.java | 26 +- .../azure/sql/SqlFirewallRuleResource.java | 49 ++-- .../java/gyro/azure/sql/SqlServerFinder.java | 20 +- .../gyro/azure/sql/SqlServerResource.java | 37 ++- .../sql/SqlVirtualNetworkRuleFinder.java | 27 +- .../sql/SqlVirtualNetworkRuleResource.java | 40 +-- 12 files changed, 464 insertions(+), 297 deletions(-) diff --git a/src/main/java/gyro/azure/sql/SqlDatabaseFinder.java b/src/main/java/gyro/azure/sql/SqlDatabaseFinder.java index 528a19a7..30383669 100644 --- a/src/main/java/gyro/azure/sql/SqlDatabaseFinder.java +++ b/src/main/java/gyro/azure/sql/SqlDatabaseFinder.java @@ -16,18 +16,18 @@ package gyro.azure.sql; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.sql.SqlDatabase; -import com.microsoft.azure.management.sql.SqlServer; -import gyro.azure.AzureFinder; -import gyro.core.Type; - import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.sql.models.SqlDatabase; +import com.azure.resourcemanager.sql.models.SqlServer; +import gyro.azure.AzureResourceManagerFinder; +import gyro.core.Type; + /** * Query sql database. * @@ -39,7 +39,8 @@ * sql-database: $(external-query azure::sql-database {}) */ @Type("sql-database") -public class SqlDatabaseFinder extends AzureFinder { +public class SqlDatabaseFinder extends AzureResourceManagerFinder { + private String sqlServerId; private String name; @@ -66,12 +67,17 @@ public void setName(String name) { } @Override - protected List findAllAzure(Azure client) { - return client.sqlServers().list().stream().map(o -> o.databases().list()).flatMap(Collection::stream).collect(Collectors.toList()); + protected List findAllAzure(AzureResourceManager client) { + return client.sqlServers() + .list() + .stream() + .map(o -> o.databases().list()) + .flatMap(Collection::stream) + .collect(Collectors.toList()); } @Override - protected List findAzure(Azure client, Map filters) { + protected List findAzure(AzureResourceManager client, Map filters) { SqlServer sqlServer = client.sqlServers().getById(filters.get("sql-server-id")); if (sqlServer == null) { diff --git a/src/main/java/gyro/azure/sql/SqlDatabaseResource.java b/src/main/java/gyro/azure/sql/SqlDatabaseResource.java index 25d196ce..e26f0b1d 100644 --- a/src/main/java/gyro/azure/sql/SqlDatabaseResource.java +++ b/src/main/java/gyro/azure/sql/SqlDatabaseResource.java @@ -16,45 +16,42 @@ package gyro.azure.sql; -import com.microsoft.azure.management.sql.DatabaseEdition; -import com.microsoft.azure.management.sql.SqlServer; -import com.microsoft.rest.ExpandableStringEnum; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import com.azure.core.util.ExpandableStringEnum; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.sql.models.CreateMode; +import com.azure.resourcemanager.sql.models.SampleName; +import com.azure.resourcemanager.sql.models.SqlDatabase; +import com.azure.resourcemanager.sql.models.SqlDatabaseBasicStorage; +import com.azure.resourcemanager.sql.models.SqlDatabaseOperations; +import com.azure.resourcemanager.sql.models.SqlDatabasePremiumServiceObjective; +import com.azure.resourcemanager.sql.models.SqlDatabasePremiumStorage; +import com.azure.resourcemanager.sql.models.SqlDatabaseStandardServiceObjective; +import com.azure.resourcemanager.sql.models.SqlDatabaseStandardStorage; +import com.azure.resourcemanager.sql.models.SqlServer; +import com.azure.resourcemanager.storage.models.StorageAccount; import com.psddev.dari.util.ObjectUtils; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.azure.storage.StorageAccountResource; import gyro.core.GyroUI; -import gyro.core.resource.Resource; -import gyro.core.resource.Output; import gyro.core.Type; +import gyro.core.resource.Output; +import gyro.core.resource.Resource; import gyro.core.resource.Updatable; - -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.sql.CreateMode; -import com.microsoft.azure.management.sql.SampleName; -import com.microsoft.azure.management.sql.SqlDatabase; -import com.microsoft.azure.management.sql.SqlDatabaseBasicStorage; -import com.microsoft.azure.management.sql.SqlDatabasePremiumServiceObjective; -import com.microsoft.azure.management.sql.SqlDatabasePremiumStorage; -import com.microsoft.azure.management.sql.SqlDatabaseStandardServiceObjective; -import com.microsoft.azure.management.sql.SqlDatabaseStandardStorage; -import com.microsoft.azure.management.sql.SqlDatabaseOperations.DefinitionStages.WithAllDifferentOptions; -import com.microsoft.azure.management.sql.SqlDatabaseOperations.DefinitionStages.WithExistingDatabaseAfterElasticPool; -import com.microsoft.azure.management.storage.StorageAccount; import gyro.core.scope.State; import gyro.core.validation.Required; import gyro.core.validation.ValidStrings; import gyro.core.validation.ValidationError; import org.apache.commons.lang.StringUtils; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - /** * Creates a sql database. * @@ -113,7 +110,15 @@ public void setCollation(String collation) { /** * The create mode of the database. */ - @ValidStrings({"Copy", "Default", "NonReadableSecondary", "OnlineSecondary", "PointInTimeRestore", "Recovery", "Restore", "RestoreLongTermRetentionBackup"}) + @ValidStrings({ + "Copy", + "Default", + "NonReadableSecondary", + "OnlineSecondary", + "PointInTimeRestore", + "Recovery", + "Restore", + "RestoreLongTermRetentionBackup" }) public String getCreateMode() { return createMode; } @@ -125,7 +130,7 @@ public void setCreateMode(String createMode) { /** * The edition of the database. */ - @ValidStrings({"Basic", "Premium", "Standard"}) + @ValidStrings({ "Basic", "Premium", "Standard" }) @Updatable public String getEdition() { return edition; @@ -307,24 +312,25 @@ public void setTags(Map tags) { @Override public void copyFrom(SqlDatabase database) { setCollation(database.collation()); - setCreateMode(database.inner().createMode() == null ? null : database.inner().createMode().toString()); + setCreateMode( + database.innerModel().createMode() == null ? null : database.innerModel().createMode().toString()); setSqlServer(findById(SqlServerResource.class, database.sqlServerName())); setElasticPool(findById(SqlElasticPoolResource.class, database.elasticPoolName())); if (getElasticPool() == null) { setEdition(database.edition().toString()); - setEditionServiceObjective(database.serviceLevelObjective().toString()); + setEditionServiceObjective(database.requestedServiceObjectiveName()); } setMaxStorageCapacity(findMaxCapacity(database.maxSizeBytes())); setId(getSqlServer().getId() + "/databases/" + getName()); setName(database.name()); - setTags(database.inner().getTags()); + setTags(database.innerModel().tags()); } @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); SqlDatabase database = getSqlDatabase(client); @@ -339,18 +345,21 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); - WithAllDifferentOptions buildDatabase = client.sqlServers().getById(getSqlServer().getId()).databases().define(getName()); + SqlDatabaseOperations.DefinitionStages.WithAllDifferentOptions buildDatabase = client.sqlServers() + .getById(getSqlServer().getId()) + .databases() + .define(getName()); //configures the source database within the elastic pool - WithExistingDatabaseAfterElasticPool withExistingDatabaseAfterElasticPool; + SqlDatabaseOperations.DefinitionStages.WithExistingDatabaseAfterElasticPool withExistingDatabaseAfterElasticPool; if (getElasticPool() != null) { withExistingDatabaseAfterElasticPool = buildDatabase.withExistingElasticPool(getElasticPool().getName()); if (getMaxStorageCapacity() != null) { withExistingDatabaseAfterElasticPool. - withMaxSizeBytes(SqlDatabasePremiumStorage.valueOf(getMaxStorageCapacity()).capacity()); + withMaxSizeBytes(SqlDatabasePremiumStorage.valueOf(getMaxStorageCapacity()).capacity()); } if (getCollation() != null) { @@ -358,22 +367,26 @@ public void create(GyroUI ui, State state) { } if (getImportFromContainerName() != null - && getImportFromFilename() != null - && getImportFromStorageAccountId() != null) - { + && getImportFromFilename() != null + && getImportFromStorageAccountId() != null) { StorageAccount storageAccount = client.storageAccounts().getById(getStorageAccount().getId()); - withExistingDatabaseAfterElasticPool.importFrom(storageAccount, + withExistingDatabaseAfterElasticPool.importFrom( + storageAccount, getImportFromContainerName(), getImportFromFilename()) - .withSqlAdministratorLoginAndPassword(getSqlServer().getAdministratorLogin(), getSqlServer().getAdministratorPassword()); + .withSqlAdministratorLoginAndPassword( + getSqlServer().getAdministratorLogin(), + getSqlServer().getAdministratorPassword()); } else if (getStorageUri() != null && getStorageAccount() != null) { buildDatabase.importFrom(getStorageUri()).withStorageAccessKey(getStorageAccount().keys().get("key1")) - .withSqlAdministratorLoginAndPassword(getSqlServer().getAdministratorLogin(), getSqlServer().getAdministratorPassword()); + .withSqlAdministratorLoginAndPassword( + getSqlServer().getAdministratorLogin(), + getSqlServer().getAdministratorPassword()); } else if (getWithSampleDatabase() != null) { withExistingDatabaseAfterElasticPool.fromSample(SampleName.ADVENTURE_WORKS_LT); } else if (getSourceDatabaseName() != null) { withExistingDatabaseAfterElasticPool.withSourceDatabase(getSourceDatabaseName()) - .withMode(CreateMode.fromString(getCreateMode())); + .withMode(CreateMode.fromString(getCreateMode())); } } else { //or create a new database @@ -383,17 +396,21 @@ && getImportFromStorageAccountId() != null) if (getEdition() != null) { if (PREMIUM_EDITION.equalsIgnoreCase(getEdition())) { if (getEditionServiceObjective() != null && getMaxStorageCapacity() != null) { - buildDatabase.withPremiumEdition(SqlDatabasePremiumServiceObjective.fromString(getEditionServiceObjective()), - SqlDatabasePremiumStorage.valueOf(getMaxStorageCapacity())); + buildDatabase.withPremiumEdition( + SqlDatabasePremiumServiceObjective.fromString(getEditionServiceObjective()), + SqlDatabasePremiumStorage.valueOf(getMaxStorageCapacity())); } else { - buildDatabase.withPremiumEdition(SqlDatabasePremiumServiceObjective.fromString(getEditionServiceObjective())); + buildDatabase.withPremiumEdition(SqlDatabasePremiumServiceObjective.fromString( + getEditionServiceObjective())); } } else if (STANDARD_EDITION.equalsIgnoreCase(getEdition())) { if (getEditionServiceObjective() != null && getMaxStorageCapacity() != null) { - buildDatabase.withStandardEdition(SqlDatabaseStandardServiceObjective.fromString(getEditionServiceObjective()), - SqlDatabaseStandardStorage.valueOf(getMaxStorageCapacity())); + buildDatabase.withStandardEdition( + SqlDatabaseStandardServiceObjective.fromString(getEditionServiceObjective()), + SqlDatabaseStandardStorage.valueOf(getMaxStorageCapacity())); } else { - buildDatabase.withStandardEdition(SqlDatabaseStandardServiceObjective.fromString(getEditionServiceObjective())); + buildDatabase.withStandardEdition(SqlDatabaseStandardServiceObjective.fromString( + getEditionServiceObjective())); } } else if (BASIC_EDITION.equalsIgnoreCase(getEdition())) { if (getMaxStorageCapacity() != null) { @@ -401,23 +418,29 @@ && getImportFromStorageAccountId() != null) } else { buildDatabase.withBasicEdition(); } - } else { - buildDatabase.withEdition(DatabaseEdition.fromString(getEdition())); } } } //pick the source of data for the database if (getSourceDatabaseName() != null && getCreateMode() != null) { - SqlDatabase db = client.sqlServers().getById(getSqlServer().getId()).databases().get(getSourceDatabaseName()); + SqlDatabase db = client.sqlServers() + .getById(getSqlServer().getId()) + .databases() + .get(getSourceDatabaseName()); buildDatabase.withSourceDatabase(db).withMode(CreateMode.fromString(getCreateMode())); - } else if (getImportFromStorageAccountId() != null && getImportFromContainerName() != null && getImportFromFilename() != null) { + } else if (getImportFromStorageAccountId() != null && getImportFromContainerName() != null + && getImportFromFilename() != null) { StorageAccount storageAccount = client.storageAccounts().getById(getImportFromStorageAccountId()); buildDatabase.importFrom(storageAccount, getImportFromContainerName(), getImportFromFilename()) - .withSqlAdministratorLoginAndPassword(getSqlServer().getAdministratorLogin(), getSqlServer().getAdministratorPassword()); + .withSqlAdministratorLoginAndPassword( + getSqlServer().getAdministratorLogin(), + getSqlServer().getAdministratorPassword()); } else if (getStorageUri() != null && getStorageAccount() != null) { buildDatabase.importFrom(getStorageUri()).withStorageAccessKey(getStorageAccount().keys().get("key1")) - .withSqlAdministratorLoginAndPassword(getSqlServer().getAdministratorLogin(), getSqlServer().getAdministratorPassword()); + .withSqlAdministratorLoginAndPassword( + getSqlServer().getAdministratorLogin(), + getSqlServer().getAdministratorPassword()); } else if (getWithSampleDatabase() != null) { buildDatabase.fromSample(SampleName.ADVENTURE_WORKS_LT); } @@ -429,7 +452,7 @@ && getImportFromStorageAccountId() != null) @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); SqlDatabase.Update update = getSqlDatabase(client).update(); @@ -440,15 +463,17 @@ public void update(GyroUI ui, State state, Resource current, Set changed if (PREMIUM_EDITION.equalsIgnoreCase(getEdition())) { if (getEditionServiceObjective() != null && getMaxStorageCapacity() != null) { - update.withPremiumEdition(SqlDatabasePremiumServiceObjective.fromString(getEditionServiceObjective()), - SqlDatabasePremiumStorage.valueOf(getMaxStorageCapacity())); + update.withPremiumEdition( + SqlDatabasePremiumServiceObjective.fromString(getEditionServiceObjective()), + SqlDatabasePremiumStorage.valueOf(getMaxStorageCapacity())); } else { update.withPremiumEdition(SqlDatabasePremiumServiceObjective.fromString(getEditionServiceObjective())); } } else if (STANDARD_EDITION.equalsIgnoreCase(getEdition())) { if (getEditionServiceObjective() != null && getMaxStorageCapacity() != null) { - update.withStandardEdition(SqlDatabaseStandardServiceObjective.fromString(getEditionServiceObjective()), - SqlDatabaseStandardStorage.valueOf(getMaxStorageCapacity())); + update.withStandardEdition( + SqlDatabaseStandardServiceObjective.fromString(getEditionServiceObjective()), + SqlDatabaseStandardStorage.valueOf(getMaxStorageCapacity())); } else { update.withStandardEdition(SqlDatabaseStandardServiceObjective.fromString(getEditionServiceObjective())); } @@ -467,7 +492,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); SqlDatabase sqlDatabase = getSqlDatabase(client); if (sqlDatabase != null) { @@ -485,7 +510,7 @@ private String findMaxCapacity(Long storage) { return null; } - private SqlDatabase getSqlDatabase(Azure client) { + private SqlDatabase getSqlDatabase(AzureResourceManager client) { SqlDatabase sqlDatabase = null; SqlServer sqlServer = client.sqlServers().getById(getSqlServer().getId()); if (sqlServer != null) { @@ -500,24 +525,59 @@ public List validate() { List errors = new ArrayList<>(); if (PREMIUM_EDITION.equalsIgnoreCase(getEdition())) { - if (!Arrays.stream(SqlDatabasePremiumStorage.values()).map(Enum::toString).collect(Collectors.toSet()).contains(getMaxStorageCapacity())) { - errors.add(new ValidationError(this, "max-storage-capacity", "Invalid value for 'max-storage-capacity' when 'edition' set to 'Premium'.")); - } else if (!SqlDatabasePremiumServiceObjective.values().stream().map(ExpandableStringEnum::toString).collect(Collectors.toSet()).contains(getEditionServiceObjective())) { - errors.add(new ValidationError(this, "edition-service-objective", "Invalid value for 'edition-service-objective' when 'edition' set to 'Premium'.")); + if (!Arrays.stream(SqlDatabasePremiumStorage.values()) + .map(Enum::toString) + .collect(Collectors.toSet()) + .contains(getMaxStorageCapacity())) { + errors.add(new ValidationError( + this, + "max-storage-capacity", + "Invalid value for 'max-storage-capacity' when 'edition' set to 'Premium'.")); + } else if (!SqlDatabasePremiumServiceObjective.values() + .stream() + .map(ExpandableStringEnum::toString) + .collect(Collectors.toSet()) + .contains(getEditionServiceObjective())) { + errors.add(new ValidationError( + this, + "edition-service-objective", + "Invalid value for 'edition-service-objective' when 'edition' set to 'Premium'.")); } } else if (STANDARD_EDITION.equalsIgnoreCase(getEdition())) { - if (!Arrays.stream(SqlDatabaseStandardStorage.values()).map(Enum::toString).collect(Collectors.toSet()).contains(getMaxStorageCapacity())) { - errors.add(new ValidationError(this, "max-storage-capacity", "Invalid value for 'max-storage-capacity' when 'edition' set to 'Standard'.")); - } else if (!SqlDatabaseStandardServiceObjective.values().stream().map(ExpandableStringEnum::toString).collect(Collectors.toSet()).contains(getEditionServiceObjective())) { - errors.add(new ValidationError(this, "edition-service-objective", "Invalid value for 'edition-service-objective' when 'edition' set to 'Standard'.")); + if (!Arrays.stream(SqlDatabaseStandardStorage.values()) + .map(Enum::toString) + .collect(Collectors.toSet()) + .contains(getMaxStorageCapacity())) { + errors.add(new ValidationError( + this, + "max-storage-capacity", + "Invalid value for 'max-storage-capacity' when 'edition' set to 'Standard'.")); + } else if (!SqlDatabaseStandardServiceObjective.values() + .stream() + .map(ExpandableStringEnum::toString) + .collect(Collectors.toSet()) + .contains(getEditionServiceObjective())) { + errors.add(new ValidationError( + this, + "edition-service-objective", + "Invalid value for 'edition-service-objective' when 'edition' set to 'Standard'.")); } } else if (BASIC_EDITION.equalsIgnoreCase(getEdition())) { - if (!Arrays.stream(SqlDatabaseBasicStorage.values()).map(Enum::toString).collect(Collectors.toSet()).contains(getMaxStorageCapacity())) { - errors.add(new ValidationError(this, "max-storage-capacity", "Invalid value for 'max-storage-capacity' when 'edition' set to 'Basic'.")); + if (!Arrays.stream(SqlDatabaseBasicStorage.values()) + .map(Enum::toString) + .collect(Collectors.toSet()) + .contains(getMaxStorageCapacity())) { + errors.add(new ValidationError( + this, + "max-storage-capacity", + "Invalid value for 'max-storage-capacity' when 'edition' set to 'Basic'.")); } if (!ObjectUtils.isBlank(getEditionServiceObjective())) { - errors.add(new ValidationError(this, "edition-service-objective", "Cannot set 'edition-service-objective' when 'edition' set to 'Basic'.")); + errors.add(new ValidationError( + this, + "edition-service-objective", + "Cannot set 'edition-service-objective' when 'edition' set to 'Basic'.")); } } diff --git a/src/main/java/gyro/azure/sql/SqlElasticPoolFinder.java b/src/main/java/gyro/azure/sql/SqlElasticPoolFinder.java index c1684346..b1173923 100644 --- a/src/main/java/gyro/azure/sql/SqlElasticPoolFinder.java +++ b/src/main/java/gyro/azure/sql/SqlElasticPoolFinder.java @@ -16,18 +16,18 @@ package gyro.azure.sql; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.sql.SqlElasticPool; -import com.microsoft.azure.management.sql.SqlServer; -import gyro.azure.AzureFinder; -import gyro.core.Type; - import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.sql.models.SqlElasticPool; +import com.azure.resourcemanager.sql.models.SqlServer; +import gyro.azure.AzureResourceManagerFinder; +import gyro.core.Type; + /** * Query sql elastic pool. * @@ -39,7 +39,8 @@ * sql-elastic-pool: $(external-query azure::sql-elastic-pool {}) */ @Type("sql-elastic-pool") -public class SqlElasticPoolFinder extends AzureFinder { +public class SqlElasticPoolFinder extends AzureResourceManagerFinder { + private String sqlServerId; private String name; @@ -66,12 +67,17 @@ public void setName(String name) { } @Override - protected List findAllAzure(Azure client) { - return client.sqlServers().list().stream().map(o -> o.elasticPools().list()).flatMap(Collection::stream).collect(Collectors.toList()); + protected List findAllAzure(AzureResourceManager client) { + return client.sqlServers() + .list() + .stream() + .map(o -> o.elasticPools().list()) + .flatMap(Collection::stream) + .collect(Collectors.toList()); } @Override - protected List findAzure(Azure client, Map filters) { + protected List findAzure(AzureResourceManager client, Map filters) { SqlServer sqlServer = client.sqlServers().getById(filters.get("sql-server-id")); if (sqlServer == null) { diff --git a/src/main/java/gyro/azure/sql/SqlElasticPoolResource.java b/src/main/java/gyro/azure/sql/SqlElasticPoolResource.java index 1aec2edc..8a229a6d 100644 --- a/src/main/java/gyro/azure/sql/SqlElasticPoolResource.java +++ b/src/main/java/gyro/azure/sql/SqlElasticPoolResource.java @@ -16,48 +16,46 @@ package gyro.azure.sql; -import com.microsoft.azure.management.sql.SqlDatabaseStandardStorage; -import com.microsoft.azure.management.sql.SqlElasticPoolOperations; -import com.microsoft.azure.management.sql.SqlServer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.sql.models.SqlDatabaseStandardStorage; +import com.azure.resourcemanager.sql.models.SqlElasticPool; +import com.azure.resourcemanager.sql.models.SqlElasticPoolBasicEDTUs; +import com.azure.resourcemanager.sql.models.SqlElasticPoolBasicMaxEDTUs; +import com.azure.resourcemanager.sql.models.SqlElasticPoolBasicMinEDTUs; +import com.azure.resourcemanager.sql.models.SqlElasticPoolOperations; +import com.azure.resourcemanager.sql.models.SqlElasticPoolPremiumEDTUs; +import com.azure.resourcemanager.sql.models.SqlElasticPoolPremiumMaxEDTUs; +import com.azure.resourcemanager.sql.models.SqlElasticPoolPremiumMinEDTUs; +import com.azure.resourcemanager.sql.models.SqlElasticPoolPremiumSorage; +import com.azure.resourcemanager.sql.models.SqlElasticPoolStandardEDTUs; +import com.azure.resourcemanager.sql.models.SqlElasticPoolStandardMaxEDTUs; +import com.azure.resourcemanager.sql.models.SqlElasticPoolStandardMinEDTUs; +import com.azure.resourcemanager.sql.models.SqlElasticPoolStandardStorage; +import com.azure.resourcemanager.sql.models.SqlServer; import com.psddev.dari.util.ObjectUtils; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.core.GyroException; import gyro.core.GyroUI; +import gyro.core.Type; import gyro.core.resource.Id; -import gyro.core.resource.Resource; import gyro.core.resource.Output; -import gyro.core.Type; +import gyro.core.resource.Resource; import gyro.core.resource.Updatable; - -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.sql.SqlElasticPool; -import com.microsoft.azure.management.sql.SqlElasticPoolBasicEDTUs; -import com.microsoft.azure.management.sql.SqlElasticPoolBasicMaxEDTUs; -import com.microsoft.azure.management.sql.SqlElasticPoolBasicMinEDTUs; -import com.microsoft.azure.management.sql.SqlElasticPoolPremiumEDTUs; -import com.microsoft.azure.management.sql.SqlElasticPoolPremiumMaxEDTUs; -import com.microsoft.azure.management.sql.SqlElasticPoolPremiumMinEDTUs; -import com.microsoft.azure.management.sql.SqlElasticPoolPremiumSorage; -import com.microsoft.azure.management.sql.SqlElasticPoolStandardEDTUs; -import com.microsoft.azure.management.sql.SqlElasticPoolStandardMaxEDTUs; -import com.microsoft.azure.management.sql.SqlElasticPoolStandardMinEDTUs; -import com.microsoft.azure.management.sql.SqlElasticPoolStandardStorage; -import com.microsoft.azure.management.sql.SqlElasticPoolOperations.DefinitionStages.WithEdition; import gyro.core.scope.State; import gyro.core.validation.Required; import gyro.core.validation.ValidStrings; import gyro.core.validation.ValidationError; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - /** * Creates a sql elastic pool. * @@ -155,7 +153,7 @@ public void setDtuReserved(String dtuReserved) { * The edition of the elastic pool. Valid values are ``Basic``, ``Premium``, or ``Standard`` */ @Required - @ValidStrings({"Basic", "Premium", "Standard"}) + @ValidStrings({ "Basic", "Premium", "Standard" }) @Updatable public String getEdition() { return edition; @@ -240,13 +238,13 @@ public void copyFrom(SqlElasticPool elasticPool) { setEdition(elasticPool.edition().toString()); setId(elasticPool.id()); setName(elasticPool.name()); - setStorageCapacity(!getEdition().equals(EDITION_BASIC) ? Integer.toString(elasticPool.storageCapacityInMB()) : null); - setTags(elasticPool.inner().getTags()); + setStorageCapacity(!getEdition().equals(EDITION_BASIC) ? Long.toString(elasticPool.storageCapacity()) : null); + setTags(elasticPool.innerModel().tags()); } @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); SqlElasticPool elasticPool = getSqlElasticPool(client); @@ -265,29 +263,32 @@ public void create(GyroUI ui, State state) { throw new GyroException("You must provide a sql server resource."); } - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); - WithEdition buildPool = client.sqlServers().getById(getSqlServer().getId()).elasticPools().define(getName()); + SqlElasticPoolOperations.DefinitionStages.WithEdition buildPool = client.sqlServers() + .getById(getSqlServer().getId()) + .elasticPools() + .define(getName()); SqlElasticPoolOperations.DefinitionStages.WithCreate elasticPool; if (EDITION_BASIC.equalsIgnoreCase(getEdition())) { elasticPool = buildPool.withBasicPool() - .withDatabaseDtuMax(SqlElasticPoolBasicMaxEDTUs.valueOf(getDtuMax())) - .withDatabaseDtuMin(SqlElasticPoolBasicMinEDTUs.valueOf(getDtuMin())) - .withReservedDtu(SqlElasticPoolBasicEDTUs.valueOf(getDtuReserved())); + .withDatabaseDtuMax(SqlElasticPoolBasicMaxEDTUs.valueOf(getDtuMax())) + .withDatabaseDtuMin(SqlElasticPoolBasicMinEDTUs.valueOf(getDtuMin())) + .withReservedDtu(SqlElasticPoolBasicEDTUs.valueOf(getDtuReserved())); } else if (EDITION_PREMIUM.equalsIgnoreCase(getEdition())) { elasticPool = buildPool.withPremiumPool() - .withDatabaseDtuMax(SqlElasticPoolPremiumMaxEDTUs.valueOf(getDtuMax())) - .withDatabaseDtuMin(SqlElasticPoolPremiumMinEDTUs.valueOf(getDtuMin())) - .withReservedDtu(SqlElasticPoolPremiumEDTUs.valueOf(getDtuReserved())) - .withStorageCapacity(SqlElasticPoolPremiumSorage.valueOf(getStorageCapacity())); + .withDatabaseDtuMax(SqlElasticPoolPremiumMaxEDTUs.valueOf(getDtuMax())) + .withDatabaseDtuMin(SqlElasticPoolPremiumMinEDTUs.valueOf(getDtuMin())) + .withReservedDtu(SqlElasticPoolPremiumEDTUs.valueOf(getDtuReserved())) + .withStorageCapacity(SqlElasticPoolPremiumSorage.valueOf(getStorageCapacity())); } else if (EDITION_STANDARD.equalsIgnoreCase(getEdition())) { elasticPool = buildPool.withStandardPool() - .withDatabaseDtuMax(SqlElasticPoolStandardMaxEDTUs.valueOf(getDtuMax())) - .withDatabaseDtuMin(SqlElasticPoolStandardMinEDTUs.valueOf(getDtuMin())) - .withReservedDtu(SqlElasticPoolStandardEDTUs.valueOf(getDtuReserved())) - .withStorageCapacity(SqlElasticPoolStandardStorage.valueOf(getStorageCapacity())); + .withDatabaseDtuMax(SqlElasticPoolStandardMaxEDTUs.valueOf(getDtuMax())) + .withDatabaseDtuMin(SqlElasticPoolStandardMinEDTUs.valueOf(getDtuMin())) + .withReservedDtu(SqlElasticPoolStandardEDTUs.valueOf(getDtuReserved())) + .withStorageCapacity(SqlElasticPoolStandardStorage.valueOf(getStorageCapacity())); } else { throw new GyroException("Invalid edition. Valid values are Basic, Standard, and Premium"); } @@ -307,24 +308,24 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); SqlElasticPool.Update update = getSqlElasticPool(client).update(); if (EDITION_BASIC.equalsIgnoreCase(getEdition())) { update.withDatabaseDtuMax(SqlElasticPoolBasicMaxEDTUs.valueOf(getDtuMax())) - .withDatabaseDtuMin(SqlElasticPoolBasicMinEDTUs.valueOf(getDtuMin())) - .withReservedDtu(SqlElasticPoolBasicEDTUs.valueOf(getDtuReserved())); + .withDatabaseDtuMin(SqlElasticPoolBasicMinEDTUs.valueOf(getDtuMin())) + .withReservedDtu(SqlElasticPoolBasicEDTUs.valueOf(getDtuReserved())); } else if (EDITION_PREMIUM.equalsIgnoreCase(getEdition())) { update.withDatabaseDtuMax(SqlElasticPoolPremiumMaxEDTUs.valueOf(getDtuMax())) - .withDatabaseDtuMin(SqlElasticPoolPremiumMinEDTUs.valueOf(getDtuMin())) - .withReservedDtu(SqlElasticPoolPremiumEDTUs.valueOf(getDtuReserved())) - .withStorageCapacity(SqlElasticPoolPremiumSorage.valueOf(getStorageCapacity())); + .withDatabaseDtuMin(SqlElasticPoolPremiumMinEDTUs.valueOf(getDtuMin())) + .withReservedDtu(SqlElasticPoolPremiumEDTUs.valueOf(getDtuReserved())) + .withStorageCapacity(SqlElasticPoolPremiumSorage.valueOf(getStorageCapacity())); } else if (EDITION_STANDARD.equalsIgnoreCase(getEdition())) { update.withDatabaseDtuMax(SqlElasticPoolStandardMaxEDTUs.valueOf(getDtuMax())) - .withDatabaseDtuMin(SqlElasticPoolStandardMinEDTUs.valueOf(getDtuMin())) - .withReservedDtu(SqlElasticPoolStandardEDTUs.valueOf(getDtuReserved())) - .withStorageCapacity(SqlElasticPoolStandardStorage.valueOf(getStorageCapacity())); + .withDatabaseDtuMin(SqlElasticPoolStandardMinEDTUs.valueOf(getDtuMin())) + .withReservedDtu(SqlElasticPoolStandardEDTUs.valueOf(getDtuReserved())) + .withStorageCapacity(SqlElasticPoolStandardStorage.valueOf(getStorageCapacity())); } for (String database : getDatabaseNames()) { @@ -336,7 +337,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); SqlElasticPool sqlElasticPool = getSqlElasticPool(client); @@ -345,7 +346,7 @@ public void delete(GyroUI ui, State state) { } } - private SqlElasticPool getSqlElasticPool(Azure client) { + private SqlElasticPool getSqlElasticPool(AzureResourceManager client) { SqlElasticPool sqlElasticPool = null; SqlServer sqlServer = client.sqlServers().getById(getSqlServer().getId()); if (sqlServer != null) { @@ -360,52 +361,121 @@ public List validate() { List errors = new ArrayList<>(); if (EDITION_PREMIUM.equalsIgnoreCase(getEdition())) { - if (!Arrays.stream(SqlElasticPoolPremiumMaxEDTUs.values()).map(Enum::toString).collect(Collectors.toSet()).contains(getDtuMax())) { - errors.add(new ValidationError(this, "dtu-max", "Invalid value for 'dtu-max' when 'edition' set to 'Premium'.")); + if (!Arrays.stream(SqlElasticPoolPremiumMaxEDTUs.values()) + .map(Enum::toString) + .collect(Collectors.toSet()) + .contains(getDtuMax())) { + errors.add(new ValidationError( + this, + "dtu-max", + "Invalid value for 'dtu-max' when 'edition' set to 'Premium'.")); } - if (!Arrays.stream(SqlElasticPoolPremiumMinEDTUs.values()).map(Enum::toString).collect(Collectors.toSet()).contains(getDtuMin())) { - errors.add(new ValidationError(this, "dtu-min", "Invalid value for 'dtu-min' when 'edition' set to 'Premium'.")); + if (!Arrays.stream(SqlElasticPoolPremiumMinEDTUs.values()) + .map(Enum::toString) + .collect(Collectors.toSet()) + .contains(getDtuMin())) { + errors.add(new ValidationError( + this, + "dtu-min", + "Invalid value for 'dtu-min' when 'edition' set to 'Premium'.")); } - if (!Arrays.stream(SqlElasticPoolPremiumEDTUs.values()).map(Enum::toString).collect(Collectors.toSet()).contains(getDtuReserved())) { - errors.add(new ValidationError(this, "dtu-reserved", "Invalid value for 'dtu-reserved' when 'edition' set to 'Premium'.")); + if (!Arrays.stream(SqlElasticPoolPremiumEDTUs.values()) + .map(Enum::toString) + .collect(Collectors.toSet()) + .contains(getDtuReserved())) { + errors.add(new ValidationError( + this, + "dtu-reserved", + "Invalid value for 'dtu-reserved' when 'edition' set to 'Premium'.")); } - if (!Arrays.stream(SqlElasticPoolPremiumSorage.values()).map(Enum::toString).collect(Collectors.toSet()).contains(getStorageCapacity())) { - errors.add(new ValidationError(this, "storage-capacity", "Invalid value for 'storage-capacity' when 'edition' set to 'Premium'.")); + if (!Arrays.stream(SqlElasticPoolPremiumSorage.values()) + .map(Enum::toString) + .collect(Collectors.toSet()) + .contains(getStorageCapacity())) { + errors.add(new ValidationError( + this, + "storage-capacity", + "Invalid value for 'storage-capacity' when 'edition' set to 'Premium'.")); } } else if (EDITION_STANDARD.equalsIgnoreCase(getEdition())) { - if (!Arrays.stream(SqlElasticPoolStandardMaxEDTUs.values()).map(Enum::toString).collect(Collectors.toSet()).contains(getDtuMax())) { - errors.add(new ValidationError(this, "dtu-max", "Invalid value for 'dtu-max' when 'edition' set to 'Standard'.")); + if (!Arrays.stream(SqlElasticPoolStandardMaxEDTUs.values()) + .map(Enum::toString) + .collect(Collectors.toSet()) + .contains(getDtuMax())) { + errors.add(new ValidationError( + this, + "dtu-max", + "Invalid value for 'dtu-max' when 'edition' set to 'Standard'.")); } - if (!Arrays.stream(SqlElasticPoolStandardMinEDTUs.values()).map(Enum::toString).collect(Collectors.toSet()).contains(getDtuMin())) { - errors.add(new ValidationError(this, "dtu-min", "Invalid value for 'dtu-min' when 'edition' set to 'Standard'.")); + if (!Arrays.stream(SqlElasticPoolStandardMinEDTUs.values()) + .map(Enum::toString) + .collect(Collectors.toSet()) + .contains(getDtuMin())) { + errors.add(new ValidationError( + this, + "dtu-min", + "Invalid value for 'dtu-min' when 'edition' set to 'Standard'.")); } - if (!Arrays.stream(SqlElasticPoolStandardEDTUs.values()).map(Enum::toString).collect(Collectors.toSet()).contains(getDtuReserved())) { - errors.add(new ValidationError(this, "dtu-reserved", "Invalid value for 'dtu-reserved' when 'edition' set to 'Standard'.")); + if (!Arrays.stream(SqlElasticPoolStandardEDTUs.values()) + .map(Enum::toString) + .collect(Collectors.toSet()) + .contains(getDtuReserved())) { + errors.add(new ValidationError( + this, + "dtu-reserved", + "Invalid value for 'dtu-reserved' when 'edition' set to 'Standard'.")); } - if (!Arrays.stream(SqlDatabaseStandardStorage.values()).map(Enum::toString).collect(Collectors.toSet()).contains(getStorageCapacity())) { - errors.add(new ValidationError(this, "storage-capacity", "Invalid value for 'storage-capacity' when 'edition' set to 'Standard'.")); + if (!Arrays.stream(SqlDatabaseStandardStorage.values()) + .map(Enum::toString) + .collect(Collectors.toSet()) + .contains(getStorageCapacity())) { + errors.add(new ValidationError( + this, + "storage-capacity", + "Invalid value for 'storage-capacity' when 'edition' set to 'Standard'.")); } } else if (EDITION_BASIC.equalsIgnoreCase(getEdition())) { - if (!Arrays.stream(SqlElasticPoolBasicMaxEDTUs.values()).map(Enum::toString).collect(Collectors.toSet()).contains(getDtuMax())) { - errors.add(new ValidationError(this, "dtu-max", "Invalid value for 'dtu-max' when 'edition' set to 'Basic'.")); + if (!Arrays.stream(SqlElasticPoolBasicMaxEDTUs.values()) + .map(Enum::toString) + .collect(Collectors.toSet()) + .contains(getDtuMax())) { + errors.add(new ValidationError( + this, + "dtu-max", + "Invalid value for 'dtu-max' when 'edition' set to 'Basic'.")); } - if (!Arrays.stream(SqlElasticPoolBasicMinEDTUs.values()).map(Enum::toString).collect(Collectors.toSet()).contains(getDtuMin())) { - errors.add(new ValidationError(this, "dtu-min", "Invalid value for 'dtu-min' when 'edition' set to 'Basic'.")); + if (!Arrays.stream(SqlElasticPoolBasicMinEDTUs.values()) + .map(Enum::toString) + .collect(Collectors.toSet()) + .contains(getDtuMin())) { + errors.add(new ValidationError( + this, + "dtu-min", + "Invalid value for 'dtu-min' when 'edition' set to 'Basic'.")); } - if (!Arrays.stream(SqlElasticPoolBasicEDTUs.values()).map(Enum::toString).collect(Collectors.toSet()).contains(getDtuReserved())) { - errors.add(new ValidationError(this, "dtu-reserved", "Invalid value for 'dtu-reserved' when 'edition' set to 'Basic'.")); + if (!Arrays.stream(SqlElasticPoolBasicEDTUs.values()) + .map(Enum::toString) + .collect(Collectors.toSet()) + .contains(getDtuReserved())) { + errors.add(new ValidationError( + this, + "dtu-reserved", + "Invalid value for 'dtu-reserved' when 'edition' set to 'Basic'.")); } if (!ObjectUtils.isBlank(getStorageCapacity())) { - errors.add(new ValidationError(this, "storage-capacity", "Cannot set 'storage-capacity' when 'edition' set to 'Basic'.")); + errors.add(new ValidationError( + this, + "storage-capacity", + "Cannot set 'storage-capacity' when 'edition' set to 'Basic'.")); } } diff --git a/src/main/java/gyro/azure/sql/SqlFailoverGroupFinder.java b/src/main/java/gyro/azure/sql/SqlFailoverGroupFinder.java index aa77b610..6653b2fb 100644 --- a/src/main/java/gyro/azure/sql/SqlFailoverGroupFinder.java +++ b/src/main/java/gyro/azure/sql/SqlFailoverGroupFinder.java @@ -16,18 +16,18 @@ package gyro.azure.sql; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.sql.SqlFailoverGroup; -import com.microsoft.azure.management.sql.SqlServer; -import gyro.azure.AzureFinder; -import gyro.core.Type; - import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.sql.models.SqlFailoverGroup; +import com.azure.resourcemanager.sql.models.SqlServer; +import gyro.azure.AzureResourceManagerFinder; +import gyro.core.Type; + /** * Query sql failover group. * @@ -39,7 +39,8 @@ * sql-failover-group: $(external-query azure::sql-failover-group {}) */ @Type("sql-failover-group") -public class SqlFailoverGroupFinder extends AzureFinder { +public class SqlFailoverGroupFinder extends AzureResourceManagerFinder { + private String sqlServerId; private String name; @@ -66,12 +67,17 @@ public void setName(String name) { } @Override - protected List findAllAzure(Azure client) { - return client.sqlServers().list().stream().map(o -> o.failoverGroups().list()).flatMap(Collection::stream).collect(Collectors.toList()); + protected List findAllAzure(AzureResourceManager client) { + return client.sqlServers() + .list() + .stream() + .map(o -> o.failoverGroups().list()) + .flatMap(Collection::stream) + .collect(Collectors.toList()); } @Override - protected List findAzure(Azure client, Map filters) { + protected List findAzure(AzureResourceManager client, Map filters) { SqlServer sqlServer = client.sqlServers().getById(filters.get("sql-server-id")); if (sqlServer == null) { diff --git a/src/main/java/gyro/azure/sql/SqlFailoverGroupResource.java b/src/main/java/gyro/azure/sql/SqlFailoverGroupResource.java index 8aeba70e..02589802 100644 --- a/src/main/java/gyro/azure/sql/SqlFailoverGroupResource.java +++ b/src/main/java/gyro/azure/sql/SqlFailoverGroupResource.java @@ -16,30 +16,28 @@ package gyro.azure.sql; -import com.microsoft.azure.management.sql.SqlServer; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.sql.models.ReadOnlyEndpointFailoverPolicy; +import com.azure.resourcemanager.sql.models.ReadWriteEndpointFailoverPolicy; +import com.azure.resourcemanager.sql.models.SqlFailoverGroup; +import com.azure.resourcemanager.sql.models.SqlFailoverGroupOperations; +import com.azure.resourcemanager.sql.models.SqlServer; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.core.GyroUI; +import gyro.core.Type; import gyro.core.resource.Id; -import gyro.core.resource.Resource; import gyro.core.resource.Output; -import gyro.core.Type; +import gyro.core.resource.Resource; import gyro.core.resource.Updatable; - -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.sql.SqlFailoverGroup; -import com.microsoft.azure.management.sql.SqlFailoverGroupOperations.DefinitionStages.WithReadWriteEndpointPolicy; -import com.microsoft.azure.management.sql.ReadOnlyEndpointFailoverPolicy; -import com.microsoft.azure.management.sql.ReadWriteEndpointFailoverPolicy; -import com.microsoft.azure.management.sql.SqlFailoverGroupOperations.DefinitionStages.WithPartnerServer; import gyro.core.scope.State; import gyro.core.validation.Required; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - /** * Creates a sql failover group. * @@ -212,7 +210,7 @@ public void copyFrom(SqlFailoverGroup failoverGroup) { @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); SqlFailoverGroup failoverGroup = getSqlFailoverGroup(client); @@ -227,16 +225,20 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); - WithReadWriteEndpointPolicy buildFailoverGroup = client.sqlServers().getById(getSqlServer().getId()).failoverGroups().define(getName()); + SqlFailoverGroupOperations.DefinitionStages.WithReadWriteEndpointPolicy buildFailoverGroup = client.sqlServers() + .getById(getSqlServer().getId()) + .failoverGroups() + .define(getName()); - WithPartnerServer withPartnerServer; + SqlFailoverGroupOperations.DefinitionStages.WithPartnerServer withPartnerServer; if (getManualReadAndWritePolicy() != null) { if (getManualReadAndWritePolicy()) { withPartnerServer = buildFailoverGroup.withManualReadWriteEndpointPolicy(); } else { - withPartnerServer = buildFailoverGroup.withAutomaticReadWriteEndpointPolicyAndDataLossGracePeriod(getReadWriteGracePeriod()); + withPartnerServer = buildFailoverGroup.withAutomaticReadWriteEndpointPolicyAndDataLossGracePeriod( + getReadWriteGracePeriod()); } for (String id : getPartnerServerIds()) { @@ -265,7 +267,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); SqlFailoverGroup.Update update = getSqlFailoverGroup(client).update(); @@ -307,7 +309,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); SqlFailoverGroup sqlFailoverGroup = getSqlFailoverGroup(client); @@ -316,7 +318,7 @@ public void delete(GyroUI ui, State state) { } } - private SqlFailoverGroup getSqlFailoverGroup(Azure client) { + private SqlFailoverGroup getSqlFailoverGroup(AzureResourceManager client) { SqlFailoverGroup sqlFailoverGroup = null; SqlServer sqlServer = client.sqlServers().getById(getSqlServer().getId()); if (sqlServer != null) { diff --git a/src/main/java/gyro/azure/sql/SqlFirewallRuleFinder.java b/src/main/java/gyro/azure/sql/SqlFirewallRuleFinder.java index 05c37f08..d5e7e478 100644 --- a/src/main/java/gyro/azure/sql/SqlFirewallRuleFinder.java +++ b/src/main/java/gyro/azure/sql/SqlFirewallRuleFinder.java @@ -16,18 +16,18 @@ package gyro.azure.sql; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.sql.SqlFirewallRule; -import com.microsoft.azure.management.sql.SqlServer; -import gyro.azure.AzureFinder; -import gyro.core.Type; - import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.sql.models.SqlFirewallRule; +import com.azure.resourcemanager.sql.models.SqlServer; +import gyro.azure.AzureResourceManagerFinder; +import gyro.core.Type; + /** * Query sql firewall rule. * @@ -39,7 +39,8 @@ * sql-firewall-rule: $(external-query azure::sql-firewall-rule {}) */ @Type("sql-firewall-rule") -public class SqlFirewallRuleFinder extends AzureFinder { +public class SqlFirewallRuleFinder extends AzureResourceManagerFinder { + private String sqlServerId; private String name; @@ -66,12 +67,17 @@ public void setName(String name) { } @Override - protected List findAllAzure(Azure client) { - return client.sqlServers().list().stream().map(o -> o.firewallRules().list()).flatMap(Collection::stream).collect(Collectors.toList()); + protected List findAllAzure(AzureResourceManager client) { + return client.sqlServers() + .list() + .stream() + .map(o -> o.firewallRules().list()) + .flatMap(Collection::stream) + .collect(Collectors.toList()); } @Override - protected List findAzure(Azure client, Map filters) { + protected List findAzure(AzureResourceManager client, Map filters) { SqlServer sqlServer = client.sqlServers().getById(filters.get("sql-server-id")); if (sqlServer == null) { diff --git a/src/main/java/gyro/azure/sql/SqlFirewallRuleResource.java b/src/main/java/gyro/azure/sql/SqlFirewallRuleResource.java index 4617efa4..1b6c9208 100644 --- a/src/main/java/gyro/azure/sql/SqlFirewallRuleResource.java +++ b/src/main/java/gyro/azure/sql/SqlFirewallRuleResource.java @@ -16,26 +16,24 @@ package gyro.azure.sql; -import com.microsoft.azure.management.sql.SqlServer; +import java.util.Set; + +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.sql.models.SqlFirewallRule; +import com.azure.resourcemanager.sql.models.SqlFirewallRuleOperations; +import com.azure.resourcemanager.sql.models.SqlServer; import com.psddev.dari.util.ObjectUtils; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.core.GyroException; import gyro.core.GyroUI; -import gyro.core.resource.Resource; -import gyro.core.resource.Output; import gyro.core.Type; +import gyro.core.resource.Output; +import gyro.core.resource.Resource; import gyro.core.resource.Updatable; - -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.sql.SqlFirewallRule; -import com.microsoft.azure.management.sql.SqlFirewallRuleOperations.DefinitionStages.WithIPAddressRange; -import com.microsoft.azure.management.sql.SqlFirewallRuleOperations.DefinitionStages.WithCreate; import gyro.core.scope.State; import gyro.core.validation.Required; -import java.util.Set; - /** * Creates a sql firewall rule. * @@ -123,15 +121,15 @@ public void setSqlServer(SqlServerResource sqlServer) { @Override public void copyFrom(SqlFirewallRule firewallRule) { setId(firewallRule.id()); - setStartIpAddress(firewallRule.startIPAddress()); - setEndIpAddress(firewallRule.endIPAddress()); + setStartIpAddress(firewallRule.startIpAddress()); + setEndIpAddress(firewallRule.endIpAddress()); setName(firewallRule.name()); setSqlServer(findById(SqlServerResource.class, firewallRule.sqlServerName())); } @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); SqlFirewallRule firewallRule = getSqlFirewallRule(client); @@ -156,15 +154,18 @@ public void create(GyroUI ui, State state) { throw new GyroException("You must provide a sql server resource."); } - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); - WithIPAddressRange rule = client.sqlServers().getById(getSqlServer().getId()).firewallRules().define(getName()); + SqlFirewallRuleOperations.DefinitionStages.WithIpAddressRange rule = client.sqlServers() + .getById(getSqlServer().getId()) + .firewallRules() + .define(getName()); - WithCreate withCreate; + SqlFirewallRuleOperations.DefinitionStages.WithCreate withCreate; if (ObjectUtils.isBlank(getEndIpAddress())) { - withCreate = rule.withIPAddress(getStartIpAddress()); + withCreate = rule.withIpAddress(getStartIpAddress()); } else { - withCreate = rule.withIPAddressRange(getStartIpAddress(), getEndIpAddress()); + withCreate = rule.withIpAddressRange(getStartIpAddress(), getEndIpAddress()); } SqlFirewallRule sqlFirewallRule = withCreate.create(); @@ -174,22 +175,22 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); SqlFirewallRule.Update update = getSqlFirewallRule(client).update(); if (ObjectUtils.isBlank(getEndIpAddress())) { - update.withStartIPAddress(getStartIpAddress()).withEndIPAddress(getStartIpAddress()).apply(); + update.withStartIpAddress(getStartIpAddress()).withEndIpAddress(getStartIpAddress()).apply(); } else { - update.withStartIPAddress(getStartIpAddress()) - .withEndIPAddress(getEndIpAddress()) + update.withStartIpAddress(getStartIpAddress()) + .withEndIpAddress(getEndIpAddress()) .apply(); } } @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); SqlFirewallRule sqlFirewallRule = getSqlFirewallRule(client); @@ -198,7 +199,7 @@ public void delete(GyroUI ui, State state) { } } - private SqlFirewallRule getSqlFirewallRule(Azure client) { + private SqlFirewallRule getSqlFirewallRule(AzureResourceManager client) { SqlFirewallRule sqlFirewallRule = null; SqlServer sqlServer = client.sqlServers().getById(getSqlServer().getId()); diff --git a/src/main/java/gyro/azure/sql/SqlServerFinder.java b/src/main/java/gyro/azure/sql/SqlServerFinder.java index 97bec805..ee862bf9 100644 --- a/src/main/java/gyro/azure/sql/SqlServerFinder.java +++ b/src/main/java/gyro/azure/sql/SqlServerFinder.java @@ -16,14 +16,15 @@ package gyro.azure.sql; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.sql.SqlServer; -import gyro.azure.AzureFinder; -import gyro.core.Type; - import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; + +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.sql.models.SqlServer; +import gyro.azure.AzureResourceManagerFinder; +import gyro.core.Type; /** * Query sql server. @@ -36,7 +37,8 @@ * sql-server: $(external-query azure::sql-server {}) */ @Type("sql-server") -public class SqlServerFinder extends AzureFinder { +public class SqlServerFinder extends AzureResourceManagerFinder { + private String id; /** @@ -51,12 +53,12 @@ public void setId(String id) { } @Override - protected List findAllAzure(Azure client) { - return client.sqlServers().list(); + protected List findAllAzure(AzureResourceManager client) { + return client.sqlServers().list().stream().collect(Collectors.toList()); } @Override - protected List findAzure(Azure client, Map filters) { + protected List findAzure(AzureResourceManager client, Map filters) { SqlServer sqlServer = filters.containsKey("id") ? client.sqlServers().getById(filters.get("id")) : null; if (sqlServer != null) { return Collections.singletonList(sqlServer); diff --git a/src/main/java/gyro/azure/sql/SqlServerResource.java b/src/main/java/gyro/azure/sql/SqlServerResource.java index 278d8d01..5b5e05d2 100644 --- a/src/main/java/gyro/azure/sql/SqlServerResource.java +++ b/src/main/java/gyro/azure/sql/SqlServerResource.java @@ -16,26 +16,25 @@ package gyro.azure.sql; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import com.azure.core.management.Region; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.sql.models.SqlServer; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.azure.resources.ResourceGroupResource; import gyro.core.GyroUI; +import gyro.core.Type; import gyro.core.resource.Id; -import gyro.core.resource.Resource; import gyro.core.resource.Output; -import gyro.core.Type; +import gyro.core.resource.Resource; import gyro.core.resource.Updatable; - -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.resources.fluentcore.arm.Region; -import com.microsoft.azure.management.sql.SqlServer; import gyro.core.scope.State; import gyro.core.validation.Required; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - /** * Creates a sql server. * @@ -203,7 +202,7 @@ public void copyFrom(SqlServer sqlServer) { @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); SqlServer sqlServer = client.sqlServers().getById(getId()); @@ -218,14 +217,14 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); SqlServer.DefinitionStages.WithCreate withCreate = client.sqlServers().define(getName()) - .withRegion(Region.fromName(getRegion())) - .withExistingResourceGroup(getResourceGroup().getName()) - .withAdministratorLogin(getAdministratorLogin()) - .withAdministratorPassword(getAdministratorPassword()) - .withTags(getTags()); + .withRegion(Region.fromName(getRegion())) + .withExistingResourceGroup(getResourceGroup().getName()) + .withAdministratorLogin(getAdministratorLogin()) + .withAdministratorPassword(getAdministratorPassword()) + .withTags(getTags()); if (getSystemAssignedMsi()) { withCreate.withSystemAssignedManagedServiceIdentity(); @@ -243,7 +242,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); SqlServer.Update update = client.sqlServers().getById(getId()).update(); @@ -258,7 +257,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); client.sqlServers().deleteById(getId()); } diff --git a/src/main/java/gyro/azure/sql/SqlVirtualNetworkRuleFinder.java b/src/main/java/gyro/azure/sql/SqlVirtualNetworkRuleFinder.java index 01b9cbbc..dc616095 100644 --- a/src/main/java/gyro/azure/sql/SqlVirtualNetworkRuleFinder.java +++ b/src/main/java/gyro/azure/sql/SqlVirtualNetworkRuleFinder.java @@ -16,18 +16,18 @@ package gyro.azure.sql; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.sql.SqlServer; -import com.microsoft.azure.management.sql.SqlVirtualNetworkRule; -import gyro.azure.AzureFinder; -import gyro.core.Type; - import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.sql.models.SqlServer; +import com.azure.resourcemanager.sql.models.SqlVirtualNetworkRule; +import gyro.azure.AzureResourceManagerFinder; +import gyro.core.Type; + /** * Query sql virtual network rule. * @@ -39,7 +39,9 @@ * sql-virtual-network-rule: $(external-query azure::sql-virtual-network-rule {}) */ @Type("sql-virtual-network-rule") -public class SqlVirtualNetworkRuleFinder extends AzureFinder { +public class SqlVirtualNetworkRuleFinder + extends AzureResourceManagerFinder { + private String sqlServerId; private String name; @@ -66,12 +68,17 @@ public void setName(String name) { } @Override - protected List findAllAzure(Azure client) { - return client.sqlServers().list().stream().map(o -> o.virtualNetworkRules().list()).flatMap(Collection::stream).collect(Collectors.toList()); + protected List findAllAzure(AzureResourceManager client) { + return client.sqlServers() + .list() + .stream() + .map(o -> o.virtualNetworkRules().list()) + .flatMap(Collection::stream) + .collect(Collectors.toList()); } @Override - protected List findAzure(Azure client, Map filters) { + protected List findAzure(AzureResourceManager client, Map filters) { SqlServer sqlServer = client.sqlServers().getById(filters.get("sql-server-id")); if (sqlServer == null) { diff --git a/src/main/java/gyro/azure/sql/SqlVirtualNetworkRuleResource.java b/src/main/java/gyro/azure/sql/SqlVirtualNetworkRuleResource.java index 0b56e800..1591093d 100644 --- a/src/main/java/gyro/azure/sql/SqlVirtualNetworkRuleResource.java +++ b/src/main/java/gyro/azure/sql/SqlVirtualNetworkRuleResource.java @@ -16,25 +16,24 @@ package gyro.azure.sql; -import com.microsoft.azure.management.sql.SqlServer; +import java.util.Set; + +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.sql.models.SqlServer; +import com.azure.resourcemanager.sql.models.SqlVirtualNetworkRule; +import com.azure.resourcemanager.sql.models.SqlVirtualNetworkRuleOperations; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.azure.network.NetworkResource; import gyro.core.GyroException; import gyro.core.GyroUI; -import gyro.core.resource.Resource; -import gyro.core.resource.Output; import gyro.core.Type; +import gyro.core.resource.Output; +import gyro.core.resource.Resource; import gyro.core.resource.Updatable; - -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.sql.SqlVirtualNetworkRule; -import com.microsoft.azure.management.sql.SqlVirtualNetworkRuleOperations.DefinitionStages.WithServiceEndpoint; import gyro.core.scope.State; import gyro.core.validation.Required; -import java.util.Set; - /** * Creates a sql virtual network rule. * @@ -132,7 +131,7 @@ public void copyFrom(SqlVirtualNetworkRule virtualNetworkRule) { @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); SqlVirtualNetworkRule virtualNetworkRule = getVirtualNetworkRule(client); @@ -150,11 +149,14 @@ public void create(GyroUI ui, State state) { if (getSqlServer() == null) { throw new GyroException("You must provide a sql server resource."); } - - Azure client = createClient(); - WithServiceEndpoint withServiceEndpoint = client.sqlServers().getById(getSqlServer().getId()).virtualNetworkRules().define(getName()) - .withSubnet(getNetwork().getId(), getSubnetName()); + AzureResourceManager client = createResourceManagerClient(); + + SqlVirtualNetworkRuleOperations.DefinitionStages.WithServiceEndpoint withServiceEndpoint = client.sqlServers() + .getById(getSqlServer().getId()) + .virtualNetworkRules() + .define(getName()) + .withSubnet(getNetwork().getId(), getSubnetName()); SqlVirtualNetworkRule virtualNetworkRule = withServiceEndpoint.create(); @@ -163,18 +165,18 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); SqlVirtualNetworkRule.Update update = getVirtualNetworkRule(client) - .update() - .withSubnet(getNetwork().getId(), getSubnetName()); + .update() + .withSubnet(getNetwork().getId(), getSubnetName()); update.apply(); } @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); SqlVirtualNetworkRule virtualNetworkRule = getVirtualNetworkRule(client); if (virtualNetworkRule != null) { @@ -182,7 +184,7 @@ public void delete(GyroUI ui, State state) { } } - private SqlVirtualNetworkRule getVirtualNetworkRule(Azure client) { + private SqlVirtualNetworkRule getVirtualNetworkRule(AzureResourceManager client) { SqlVirtualNetworkRule sqlVirtualNetworkRule = null; SqlServer sqlServer = client.sqlServers().getById(getSqlServer().getId()); From e45ff5005e0809c5b6ee33afcf5488e3910ba07f Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Wed, 25 May 2022 15:02:16 -0400 Subject: [PATCH 30/43] Initial compute refactor --- .../azure/compute/AdditionalCapability.java | 7 +- .../azure/compute/AvailabilitySetFinder.java | 21 +- .../compute/AvailabilitySetResource.java | 54 +-- .../java/gyro/azure/compute/DiskFinder.java | 20 +- .../java/gyro/azure/compute/DiskResource.java | 48 +- .../azure/compute/LoadBalancerAttachment.java | 7 +- .../ProximityPlacementGroupResource.java | 19 +- .../azure/compute/ScalingFixedSchedule.java | 3 +- .../gyro/azure/compute/ScalingProfile.java | 23 +- .../compute/ScalingRecurrentSchedule.java | 16 +- .../java/gyro/azure/compute/ScalingRule.java | 89 ++-- .../gyro/azure/compute/SnapshotFinder.java | 20 +- .../gyro/azure/compute/SnapshotResource.java | 65 ++- .../gyro/azure/compute/VMScaleSetFinder.java | 20 +- .../azure/compute/VMScaleSetResource.java | 200 +++++--- .../compute/VMScaleSetScalingFinder.java | 20 +- .../compute/VMScaleSetScalingResource.java | 75 ++- .../compute/VMScaleSetVirtualMachine.java | 20 +- .../azure/compute/VirtualMachineFinder.java | 21 +- .../compute/VirtualMachineImageFinder.java | 21 +- .../compute/VirtualMachineImageResource.java | 31 +- .../azure/compute/VirtualMachineResource.java | 452 +++++++++++------- 22 files changed, 743 insertions(+), 509 deletions(-) diff --git a/src/main/java/gyro/azure/compute/AdditionalCapability.java b/src/main/java/gyro/azure/compute/AdditionalCapability.java index 17b2807e..74c8fba1 100644 --- a/src/main/java/gyro/azure/compute/AdditionalCapability.java +++ b/src/main/java/gyro/azure/compute/AdditionalCapability.java @@ -16,12 +16,13 @@ package gyro.azure.compute; -import com.microsoft.azure.management.compute.AdditionalCapabilities; +import com.azure.resourcemanager.compute.models.AdditionalCapabilities; import gyro.azure.Copyable; import gyro.core.resource.Diffable; import gyro.core.resource.Updatable; public class AdditionalCapability extends Diffable implements Copyable { + private Boolean ultraSSDEnabled; /** @@ -42,12 +43,12 @@ public void setUltraSSDEnabled(Boolean ultraSSDEnabled) { @Override public void copyFrom(AdditionalCapabilities additionalCapabilities) { - setUltraSSDEnabled(additionalCapabilities.ultraSSDEnabled()); + setUltraSSDEnabled(additionalCapabilities.ultraSsdEnabled()); } AdditionalCapabilities toAdditionalCapabilities() { AdditionalCapabilities capabilities = new AdditionalCapabilities(); - capabilities.withUltraSSDEnabled(getUltraSSDEnabled()); + capabilities.withUltraSsdEnabled(getUltraSSDEnabled()); return capabilities; } diff --git a/src/main/java/gyro/azure/compute/AvailabilitySetFinder.java b/src/main/java/gyro/azure/compute/AvailabilitySetFinder.java index 48447c2f..d4320645 100644 --- a/src/main/java/gyro/azure/compute/AvailabilitySetFinder.java +++ b/src/main/java/gyro/azure/compute/AvailabilitySetFinder.java @@ -16,14 +16,15 @@ package gyro.azure.compute; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.compute.AvailabilitySet; -import gyro.azure.AzureFinder; -import gyro.core.Type; - import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; + +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.compute.models.AvailabilitySet; +import gyro.azure.AzureResourceManagerFinder; +import gyro.core.Type; /** * Query availability set. @@ -36,7 +37,8 @@ * availability-set: $(external-query azure::availability-set {}) */ @Type("availability-set") -public class AvailabilitySetFinder extends AzureFinder { +public class AvailabilitySetFinder extends AzureResourceManagerFinder { + private String id; /** @@ -49,13 +51,14 @@ public String getId() { public void setId(String id) { this.id = id; } + @Override - protected List findAllAzure(Azure client) { - return client.availabilitySets().list(); + protected List findAllAzure(AzureResourceManager client) { + return client.availabilitySets().list().stream().collect(Collectors.toList()); } @Override - protected List findAzure(Azure client, Map filters) { + protected List findAzure(AzureResourceManager client, Map filters) { AvailabilitySet availabilitySet = client.availabilitySets().getById(filters.get("id")); if (availabilitySet == null) { return Collections.emptyList(); diff --git a/src/main/java/gyro/azure/compute/AvailabilitySetResource.java b/src/main/java/gyro/azure/compute/AvailabilitySetResource.java index fc68ae66..34ab2e94 100644 --- a/src/main/java/gyro/azure/compute/AvailabilitySetResource.java +++ b/src/main/java/gyro/azure/compute/AvailabilitySetResource.java @@ -16,29 +16,28 @@ package gyro.azure.compute; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import com.azure.core.management.Region; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.compute.models.AvailabilitySet; +import com.azure.resourcemanager.compute.models.AvailabilitySetSkuTypes; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.azure.resources.ResourceGroupResource; import gyro.core.GyroException; import gyro.core.GyroUI; -import gyro.core.resource.Id; -import gyro.core.resource.Updatable; import gyro.core.Type; +import gyro.core.resource.Id; import gyro.core.resource.Output; import gyro.core.resource.Resource; - -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.compute.AvailabilitySet; -import com.microsoft.azure.management.compute.AvailabilitySetSkuTypes; -import com.microsoft.azure.management.resources.fluentcore.arm.Region; +import gyro.core.resource.Updatable; import gyro.core.scope.State; import gyro.core.validation.Required; import gyro.core.validation.ValidStrings; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - /** * Creates an availability set. * @@ -100,8 +99,8 @@ public void setId(String id) { @Required public String getName() { return name != null - ? name.toUpperCase() - : name; + ? name.toUpperCase() + : name; } public void setName(String name) { @@ -123,14 +122,14 @@ public void setResourceGroup(ResourceGroupResource resourceGroup) { /** * The Availability Set sku. Defaults to ``Classic``. */ - @ValidStrings({"Aligned", "Classic"}) + @ValidStrings({ "Aligned", "Classic" }) @Updatable public String getSku() { if (sku == null) { sku = "Classic"; } - return sku; + return sku; } public void setSku(String sku) { @@ -176,7 +175,7 @@ public void copyFrom(AvailabilitySet availabilitySet) { @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); AvailabilitySet availabilitySet = client.availabilitySets().getById(getId()); @@ -191,25 +190,26 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); AvailabilitySet availabilitySet = client.availabilitySets().define(getName()) - .withRegion(Region.fromName(getRegion())) - .withExistingResourceGroup(getResourceGroup().getName()) - .withFaultDomainCount(getFaultDomainCount()) - .withSku(AvailabilitySetSkuTypes.fromString(getSku())) - .withUpdateDomainCount(getUpdateDomainCount()) - .withTags(getTags()) - .create(); + .withRegion(Region.fromName(getRegion())) + .withExistingResourceGroup(getResourceGroup().getName()) + .withFaultDomainCount(getFaultDomainCount()) + .withSku(AvailabilitySetSkuTypes.fromString(getSku())) + .withUpdateDomainCount(getUpdateDomainCount()) + .withTags(getTags()) + .create(); copyFrom(availabilitySet); } @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); - if (changedFieldNames.contains("sku") && AvailabilitySetSkuTypes.fromString(getSku()).equals(AvailabilitySetSkuTypes.CLASSIC)) { + if (changedFieldNames.contains("sku") && AvailabilitySetSkuTypes.fromString(getSku()) + .equals(AvailabilitySetSkuTypes.CLASSIC)) { throw new GyroException("Changing param SKU from 'Aligned' to 'Classic' is not allowed"); } @@ -223,7 +223,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); client.availabilitySets().deleteById(getId()); } diff --git a/src/main/java/gyro/azure/compute/DiskFinder.java b/src/main/java/gyro/azure/compute/DiskFinder.java index 2464b49b..37d6bea1 100644 --- a/src/main/java/gyro/azure/compute/DiskFinder.java +++ b/src/main/java/gyro/azure/compute/DiskFinder.java @@ -16,14 +16,15 @@ package gyro.azure.compute; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.compute.Disk; -import gyro.azure.AzureFinder; -import gyro.core.Type; - import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; + +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.compute.models.Disk; +import gyro.azure.AzureResourceManagerFinder; +import gyro.core.Type; /** * Query disk. @@ -36,7 +37,8 @@ * disk: $(external-query azure::disk {}) */ @Type("disk") -public class DiskFinder extends AzureFinder { +public class DiskFinder extends AzureResourceManagerFinder { + private String id; /** @@ -51,12 +53,12 @@ public void setId(String id) { } @Override - protected List findAllAzure(Azure client) { - return client.disks().list(); + protected List findAllAzure(AzureResourceManager client) { + return client.disks().list().stream().collect(Collectors.toList()); } @Override - protected List findAzure(Azure client, Map filters) { + protected List findAzure(AzureResourceManager client, Map filters) { Disk disk = client.disks().getById(filters.get("id")); if (disk == null) { return Collections.emptyList(); diff --git a/src/main/java/gyro/azure/compute/DiskResource.java b/src/main/java/gyro/azure/compute/DiskResource.java index 2a5dc981..2ec2e313 100644 --- a/src/main/java/gyro/azure/compute/DiskResource.java +++ b/src/main/java/gyro/azure/compute/DiskResource.java @@ -16,34 +16,34 @@ package gyro.azure.compute; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.compute.Disk; -import com.microsoft.azure.management.compute.DiskSkuTypes; -import com.microsoft.azure.management.compute.DiskStorageAccountTypes; -import com.microsoft.azure.management.compute.OperatingSystemTypes; -import com.microsoft.azure.management.resources.fluentcore.arm.Region; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.azure.core.management.Region; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.compute.models.Disk; +import com.azure.resourcemanager.compute.models.DiskSkuTypes; +import com.azure.resourcemanager.compute.models.DiskStorageAccountTypes; +import com.azure.resourcemanager.compute.models.OperatingSystemTypes; import com.psddev.dari.util.ObjectUtils; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.azure.resources.ResourceGroupResource; import gyro.azure.storage.StorageAccountResource; import gyro.core.GyroUI; -import gyro.core.resource.Id; -import gyro.core.resource.Updatable; import gyro.core.Type; +import gyro.core.resource.Id; import gyro.core.resource.Output; import gyro.core.resource.Resource; +import gyro.core.resource.Updatable; import gyro.core.scope.State; import gyro.core.validation.Required; import gyro.core.validation.ValidStrings; import gyro.core.validation.ValidationError; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - /** * Creates a disk. * @@ -65,6 +65,7 @@ */ @Type("disk") public class DiskResource extends AzureResource implements Copyable { + private String name; private String id; private ResourceGroupResource resourceGroup; @@ -130,7 +131,7 @@ public void setSize(Integer size) { * Type of OS. */ @Required - @ValidStrings({"LINUX", "WINDOWS"}) + @ValidStrings({ "LINUX", "WINDOWS" }) @Updatable public String getOsType() { return osType != null ? osType.toUpperCase() : null; @@ -144,7 +145,7 @@ public void setOsType(String osType) { * Type of Disk. */ @Required - @ValidStrings({"STANDARD_LRS", "PREMIUM_LRS", "STANDARDSSD_LRS", "ULTRASSD_LRS"}) + @ValidStrings({ "STANDARD_LRS", "PREMIUM_LRS", "STANDARDSSD_LRS", "ULTRASSD_LRS" }) @Updatable public String getType() { return type != null ? type.toUpperCase() : null; @@ -157,7 +158,7 @@ public void setType(String type) { /** * Type of data source. Defaults to ``disk``. */ - @ValidStrings({"disk", "vhd", "snapshot"}) + @ValidStrings({ "disk", "vhd", "snapshot" }) public String getDataLoadSourceType() { if (dataLoadSourceType == null) { dataLoadSourceType = "disk"; @@ -220,7 +221,7 @@ public void copyFrom(Disk disk) { @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); Disk disk = client.disks().getById(getId()); @@ -235,7 +236,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); Disk.DefinitionStages.WithDiskSource diskDefWithoutData = client.disks() .define(getName()) @@ -290,7 +291,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); Disk disk = client.disks().getById(getId()); @@ -317,7 +318,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); client.disks().deleteById(getId()); } @@ -327,7 +328,10 @@ public List validate() { List errors = new ArrayList<>(); if (getDataLoadSourceType().equals("vhd") && getDataLoadSourceStorageAccount() == null) { - errors.add(new ValidationError(this, "data-load-source-storage-account", "required when `data-load-source-type` is set to `vhd`.")); + errors.add(new ValidationError( + this, + "data-load-source-storage-account", + "required when `data-load-source-type` is set to `vhd`.")); } return errors; diff --git a/src/main/java/gyro/azure/compute/LoadBalancerAttachment.java b/src/main/java/gyro/azure/compute/LoadBalancerAttachment.java index ce2f2823..62c8d5a4 100644 --- a/src/main/java/gyro/azure/compute/LoadBalancerAttachment.java +++ b/src/main/java/gyro/azure/compute/LoadBalancerAttachment.java @@ -16,15 +16,16 @@ package gyro.azure.compute; +import java.util.HashSet; +import java.util.Set; + import gyro.azure.network.LoadBalancerResource; import gyro.core.resource.Diffable; import gyro.core.resource.Updatable; import gyro.core.validation.Required; -import java.util.HashSet; -import java.util.Set; - public class LoadBalancerAttachment extends Diffable { + private LoadBalancerResource loadBalancer; private Set backends; private Set inboundNatPools; diff --git a/src/main/java/gyro/azure/compute/ProximityPlacementGroupResource.java b/src/main/java/gyro/azure/compute/ProximityPlacementGroupResource.java index fe78c573..b7adcf4e 100644 --- a/src/main/java/gyro/azure/compute/ProximityPlacementGroupResource.java +++ b/src/main/java/gyro/azure/compute/ProximityPlacementGroupResource.java @@ -16,7 +16,10 @@ package gyro.azure.compute; -import com.microsoft.azure.management.compute.ProximityPlacementGroup; +import java.util.Set; +import java.util.stream.Collectors; + +import com.azure.resourcemanager.compute.models.ProximityPlacementGroup; import gyro.azure.Copyable; import gyro.azure.resources.ResourceGroupResource; import gyro.core.resource.Diffable; @@ -24,10 +27,8 @@ import gyro.core.validation.Required; import gyro.core.validation.ValidStrings; -import java.util.Set; -import java.util.stream.Collectors; - public class ProximityPlacementGroupResource extends Diffable implements Copyable { + private String name; private String type; private String id; @@ -50,7 +51,7 @@ public void setName(String name) { /** * The type of the Proximity Placement Group. Defaults to ``STANDARD``. */ - @ValidStrings({"STANDARD", "ULTRA"}) + @ValidStrings({ "STANDARD", "ULTRA" }) public String getType() { if (type != null) { type = type.toUpperCase(); @@ -113,12 +114,16 @@ public void setAvailabilitySets(Set availabilitySets) { @Override public void copyFrom(ProximityPlacementGroup proximityPlacementGroup) { - setAvailabilitySets(proximityPlacementGroup.availabilitySetIds() != null ? proximityPlacementGroup.availabilitySetIds().stream().map(o -> findById(AvailabilitySetResource.class, o)).collect(Collectors.toSet()) : null); + setAvailabilitySets( + proximityPlacementGroup.availabilitySetIds() != null ? proximityPlacementGroup.availabilitySetIds() + .stream() + .map(o -> findById(AvailabilitySetResource.class, o)) + .collect(Collectors.toSet()) : null); setId(proximityPlacementGroup.id()); setLocation(proximityPlacementGroup.location()); setResourceGroup(findById(ResourceGroupResource.class, proximityPlacementGroup.resourceGroupName())); setType(proximityPlacementGroup.proximityPlacementGroupType().toString()); - setName(proximityPlacementGroup.inner().name()); + setName(proximityPlacementGroup.innerModel().name()); } @Override diff --git a/src/main/java/gyro/azure/compute/ScalingFixedSchedule.java b/src/main/java/gyro/azure/compute/ScalingFixedSchedule.java index 3802e093..dbc84062 100644 --- a/src/main/java/gyro/azure/compute/ScalingFixedSchedule.java +++ b/src/main/java/gyro/azure/compute/ScalingFixedSchedule.java @@ -16,12 +16,13 @@ package gyro.azure.compute; -import com.microsoft.azure.management.monitor.TimeWindow; +import com.azure.resourcemanager.monitor.models.TimeWindow; import gyro.azure.Copyable; import gyro.core.resource.Diffable; import gyro.core.validation.Required; public class ScalingFixedSchedule extends Diffable implements Copyable { + private String startTime; private String endTime; private String timeZone; diff --git a/src/main/java/gyro/azure/compute/ScalingProfile.java b/src/main/java/gyro/azure/compute/ScalingProfile.java index 868fe725..f67c6f70 100644 --- a/src/main/java/gyro/azure/compute/ScalingProfile.java +++ b/src/main/java/gyro/azure/compute/ScalingProfile.java @@ -16,19 +16,19 @@ package gyro.azure.compute; -import com.microsoft.azure.management.monitor.AutoscaleProfile; +import java.util.HashSet; +import java.util.Set; +import java.util.stream.Collectors; + +import com.azure.resourcemanager.monitor.models.AutoscaleProfile; import gyro.azure.Copyable; import gyro.core.resource.Diffable; import gyro.core.resource.Updatable; import gyro.core.validation.Required; import gyro.core.validation.ValidStrings; -import java.util.HashSet; -import java.util.Set; -import java.util.stream.Collectors; - public class ScalingProfile extends Diffable implements Copyable { - public enum ProfileType {FIXED, RECURRENT_SCHEDULE, FIXED_SCHEDULE, METRIC} + private String name; private ProfileType type; private Integer defaultInstanceCount; @@ -55,7 +55,7 @@ public void setName(String name) { */ @Required @Updatable - @ValidStrings({"FIXED", "RECURRENT_SCHEDULE", "FIXED_SCHEDULE", "METRIC"}) + @ValidStrings({ "FIXED", "RECURRENT_SCHEDULE", "FIXED_SCHEDULE", "METRIC" }) public ProfileType getType() { return type; } @@ -163,7 +163,7 @@ public void copyFrom(AutoscaleProfile profile) { ScalingRecurrentSchedule schedule = newSubresource(ScalingRecurrentSchedule.class); schedule.copyFrom(profile.recurrentSchedule()); setRecurrentSchedule(schedule); - } else if (profile.rules() != null && !profile.rules().isEmpty()){ + } else if (profile.rules() != null && !profile.rules().isEmpty()) { setType(ProfileType.METRIC); setRule(profile.rules().stream().map(o -> { ScalingRule rule = newSubresource(ScalingRule.class); @@ -179,4 +179,11 @@ public void copyFrom(AutoscaleProfile profile) { public String primaryKey() { return getName(); } + + public enum ProfileType { + FIXED, + RECURRENT_SCHEDULE, + FIXED_SCHEDULE, + METRIC + } } diff --git a/src/main/java/gyro/azure/compute/ScalingRecurrentSchedule.java b/src/main/java/gyro/azure/compute/ScalingRecurrentSchedule.java index 31237801..6124f16e 100644 --- a/src/main/java/gyro/azure/compute/ScalingRecurrentSchedule.java +++ b/src/main/java/gyro/azure/compute/ScalingRecurrentSchedule.java @@ -16,18 +16,19 @@ package gyro.azure.compute; -import com.microsoft.azure.management.monitor.DayOfWeek; -import com.microsoft.azure.management.monitor.Recurrence; +import java.util.Set; +import java.util.stream.Collectors; + +import com.azure.resourcemanager.monitor.models.DayOfWeek; +import com.azure.resourcemanager.monitor.models.Recurrence; import gyro.azure.Copyable; import gyro.core.resource.Diffable; import gyro.core.resource.Updatable; import gyro.core.validation.Required; import gyro.core.validation.ValidStrings; -import java.util.Set; -import java.util.stream.Collectors; - public class ScalingRecurrentSchedule extends Diffable implements Copyable { + private String timeZone; private String startTime; private Set dayOfWeeks; @@ -61,7 +62,7 @@ public void setStartTime(String startTime) { */ @Required @Updatable - @ValidStrings({"MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY"}) + @ValidStrings({ "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY" }) public Set getDayOfWeeks() { return dayOfWeeks; } @@ -76,7 +77,8 @@ public void copyFrom(Recurrence recurrence) { setDayOfWeeks(recurrence.schedule().days().stream().map(String::toUpperCase).collect(Collectors.toSet())); String hours = recurrence.schedule().hours().get(0).toString(); String minutes = recurrence.schedule().minutes().get(0).toString(); - setStartTime((hours.length() == 1 ? "0" + hours : hours) + ":" + (minutes.length() == 1 ? "0" + minutes : minutes)); + setStartTime( + (hours.length() == 1 ? "0" + hours : hours) + ":" + (minutes.length() == 1 ? "0" + minutes : minutes)); } DayOfWeek[] toDayOfWeeks() { diff --git a/src/main/java/gyro/azure/compute/ScalingRule.java b/src/main/java/gyro/azure/compute/ScalingRule.java index f91ebea3..88fd0ac3 100644 --- a/src/main/java/gyro/azure/compute/ScalingRule.java +++ b/src/main/java/gyro/azure/compute/ScalingRule.java @@ -16,32 +16,34 @@ package gyro.azure.compute; -import com.microsoft.azure.management.monitor.ComparisonOperationType; -import com.microsoft.azure.management.monitor.MetricStatisticType; -import com.microsoft.azure.management.monitor.ScaleDirection; -import com.microsoft.azure.management.monitor.ScaleRule; -import com.microsoft.azure.management.monitor.ScaleType; -import com.microsoft.azure.management.monitor.TimeAggregationType; +import java.time.Duration; + +import com.azure.resourcemanager.monitor.models.ComparisonOperationType; +import com.azure.resourcemanager.monitor.models.MetricStatisticType; +import com.azure.resourcemanager.monitor.models.ScaleDirection; +import com.azure.resourcemanager.monitor.models.ScaleRule; +import com.azure.resourcemanager.monitor.models.ScaleType; +import com.azure.resourcemanager.monitor.models.TimeAggregationType; import gyro.azure.Copyable; import gyro.core.resource.Diffable; import gyro.core.resource.Updatable; import gyro.core.validation.Range; import gyro.core.validation.Required; import gyro.core.validation.ValidStrings; -import org.joda.time.Period; public class ScalingRule extends Diffable implements Copyable { + private String metricName; private String metricSourceId; private MetricStatisticType statisticType; - private Integer statisticDuration; - private Integer statisticFrequency; + private Long statisticDuration; + private Long statisticFrequency; private TimeAggregationType timeAggregation; private ComparisonOperationType comparisonOperation; private Double threshold; private ScaleDirection scaleDirection; private ScaleType scaleType; - private Integer cooldown; + private Long cooldown; private Integer instanceCountChange; /** @@ -72,7 +74,7 @@ public void setMetricSourceId(String metricSourceId) { * The type of metrics statistic showing how metrics from multiple instances are combined. Defaults to ``AVERAGE``. */ @Updatable - @ValidStrings({"AVERAGE", "MIN", "MAX", "SUM"}) + @ValidStrings({ "AVERAGE", "MIN", "MAX", "SUM" }) public MetricStatisticType getStatisticType() { if (statisticType == null) { statisticType = MetricStatisticType.AVERAGE; @@ -90,15 +92,15 @@ public void setStatisticType(MetricStatisticType statisticType) { */ @Range(min = 300, max = 43200) @Updatable - public Integer getStatisticDuration() { + public Long getStatisticDuration() { if (statisticDuration == null) { - statisticDuration = 600; + statisticDuration = 600L; } return statisticDuration; } - public void setStatisticDuration(Integer statisticDuration) { + public void setStatisticDuration(Long statisticDuration) { this.statisticDuration = statisticDuration; } @@ -107,15 +109,15 @@ public void setStatisticDuration(Integer statisticDuration) { */ @Range(min = 60, max = 43200) @Updatable - public Integer getStatisticFrequency() { + public Long getStatisticFrequency() { if (statisticFrequency == null) { - statisticFrequency = 60; + statisticFrequency = 60L; } return statisticFrequency; } - public void setStatisticFrequency(Integer statisticFrequency) { + public void setStatisticFrequency(Long statisticFrequency) { this.statisticFrequency = statisticFrequency; } @@ -124,7 +126,7 @@ public void setStatisticFrequency(Integer statisticFrequency) { */ @Required @Updatable - @ValidStrings({"AVERAGE", "MINIMUM", "MAXIMUM", "TOTAL", "COUNT"}) + @ValidStrings({ "AVERAGE", "MINIMUM", "MAXIMUM", "TOTAL", "COUNT" }) public TimeAggregationType getTimeAggregation() { return timeAggregation; } @@ -138,7 +140,13 @@ public void setTimeAggregation(TimeAggregationType timeAggregation) { */ @Required @Updatable - @ValidStrings({"EQUALS", "NOT_EQUALS", "GREATER_THAN", "GREATER_THAN_OR_EQUAL", "LESS_THAN", "LESS_THAN_OR_EQUAL"}) + @ValidStrings({ + "EQUALS", + "NOT_EQUALS", + "GREATER_THAN", + "GREATER_THAN_OR_EQUAL", + "LESS_THAN", + "LESS_THAN_OR_EQUAL" }) public ComparisonOperationType getComparisonOperation() { return comparisonOperation; } @@ -165,7 +173,7 @@ public void setThreshold(Double threshold) { */ @Required @Updatable - @ValidStrings({"NONE", "INCREASE", "DECREASE"}) + @ValidStrings({ "NONE", "INCREASE", "DECREASE" }) public ScaleDirection getScaleDirection() { return scaleDirection; } @@ -179,7 +187,7 @@ public void setScaleDirection(ScaleDirection scaleDirection) { */ @Required @Updatable - @ValidStrings({"CHANGE_COUNT", "PERCENT_CHANGE_COUNT", "EXACT_COUNT"}) + @ValidStrings({ "CHANGE_COUNT", "PERCENT_CHANGE_COUNT", "EXACT_COUNT" }) public ScaleType getScaleType() { return scaleType; } @@ -194,11 +202,11 @@ public void setScaleType(ScaleType scaleType) { @Required @Updatable @Range(min = 1, max = 10080) - public Integer getCooldown() { + public Long getCooldown() { return cooldown; } - public void setCooldown(Integer cooldown) { + public void setCooldown(Long cooldown) { this.cooldown = cooldown; } @@ -218,9 +226,9 @@ public void setInstanceCountChange(Integer instanceCountChange) { @Override public void copyFrom(ScaleRule rule) { setComparisonOperation(rule.condition()); - setCooldown(rule.coolDown().toStandardMinutes().getMinutes()); - setStatisticDuration(rule.duration().toStandardSeconds().getSeconds()); - setStatisticFrequency(rule.frequency().toStandardSeconds().getSeconds()); + setCooldown(rule.cooldown().toMinutes()); + setStatisticDuration(rule.duration().toSeconds()); + setStatisticFrequency(rule.frequency().toSeconds()); setStatisticType(rule.frequencyStatistic()); setMetricName(rule.metricName()); setMetricSourceId(rule.metricSource()); @@ -234,17 +242,31 @@ public void copyFrom(ScaleRule rule) { ScaleRule.DefinitionStages.WithAttach attachRule(ScaleRule.DefinitionStages.Blank withBlank) { return withBlank.withMetricSource(getMetricSourceId()) .withMetricName(getMetricName()) - .withStatistic(Period.seconds(getStatisticDuration()), Period.seconds(getStatisticFrequency()), getStatisticType()) + .withStatistic( + Duration.ofSeconds(getStatisticDuration()), + Duration.ofSeconds(getStatisticFrequency()), + getStatisticType()) .withCondition(getTimeAggregation(), getComparisonOperation(), getThreshold()) - .withScaleAction(getScaleDirection(), getScaleType(), getInstanceCountChange(), Period.minutes(getCooldown())); + .withScaleAction( + getScaleDirection(), + getScaleType(), + getInstanceCountChange(), + Duration.ofMinutes(getCooldown())); } ScaleRule.ParentUpdateDefinitionStages.WithAttach attachRule(ScaleRule.ParentUpdateDefinitionStages.Blank withBlank) { return withBlank.withMetricSource(getMetricSourceId()) .withMetricName(getMetricName()) - .withStatistic(Period.seconds(getStatisticDuration()), Period.seconds(getStatisticFrequency()), getStatisticType()) + .withStatistic( + Duration.ofSeconds(getStatisticDuration()), + Duration.ofSeconds(getStatisticFrequency()), + getStatisticType()) .withCondition(getTimeAggregation(), getComparisonOperation(), getThreshold()) - .withScaleAction(getScaleDirection(), getScaleType(), getInstanceCountChange(), Period.minutes(getCooldown())); + .withScaleAction( + getScaleDirection(), + getScaleType(), + getInstanceCountChange(), + Duration.ofMinutes(getCooldown())); } @Override @@ -252,6 +274,11 @@ public String primaryKey() { String format = String.format("%s %s %s %s %s %s %s %s %s", getStatisticType(), getStatisticDuration(), getStatisticFrequency(), getTimeAggregation(), getComparisonOperation(), getThreshold(), getScaleType(), getCooldown(), getInstanceCountChange()); - return String.format("Rule (%s with direction %s for target %s) %s", getMetricName(), getScaleDirection(), getMetricSourceId(), format.hashCode()); + return String.format( + "Rule (%s with direction %s for target %s) %s", + getMetricName(), + getScaleDirection(), + getMetricSourceId(), + format.hashCode()); } } diff --git a/src/main/java/gyro/azure/compute/SnapshotFinder.java b/src/main/java/gyro/azure/compute/SnapshotFinder.java index e5c0cfc4..359dd49f 100644 --- a/src/main/java/gyro/azure/compute/SnapshotFinder.java +++ b/src/main/java/gyro/azure/compute/SnapshotFinder.java @@ -16,14 +16,15 @@ package gyro.azure.compute; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.compute.Snapshot; -import gyro.azure.AzureFinder; -import gyro.core.Type; - import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; + +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.compute.models.Snapshot; +import gyro.azure.AzureResourceManagerFinder; +import gyro.core.Type; /** * Query snapshot. @@ -36,7 +37,8 @@ * snapshot: $(external-query azure::snapshot {}) */ @Type("snapshot") -public class SnapshotFinder extends AzureFinder { +public class SnapshotFinder extends AzureResourceManagerFinder { + private String id; /** @@ -51,12 +53,12 @@ public void setId(String id) { } @Override - protected List findAllAzure(Azure client) { - return client.snapshots().list(); + protected List findAllAzure(AzureResourceManager client) { + return client.snapshots().list().stream().collect(Collectors.toList()); } @Override - protected List findAzure(Azure client, Map filters) { + protected List findAzure(AzureResourceManager client, Map filters) { Snapshot snapshot = client.snapshots().getById(filters.get("id")); if (snapshot == null) { return Collections.emptyList(); diff --git a/src/main/java/gyro/azure/compute/SnapshotResource.java b/src/main/java/gyro/azure/compute/SnapshotResource.java index 97b7d954..ff4a4de9 100644 --- a/src/main/java/gyro/azure/compute/SnapshotResource.java +++ b/src/main/java/gyro/azure/compute/SnapshotResource.java @@ -16,33 +16,31 @@ package gyro.azure.compute; -import com.microsoft.azure.management.compute.CreationSourceType; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import com.azure.core.management.Region; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.compute.models.CreationSourceType; +import com.azure.resourcemanager.compute.models.Snapshot; +import com.azure.resourcemanager.compute.models.SnapshotSkuType; +import com.azure.resourcemanager.compute.models.SnapshotStorageAccountTypes; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.azure.resources.ResourceGroupResource; import gyro.core.GyroException; import gyro.core.GyroUI; +import gyro.core.Type; import gyro.core.resource.Id; +import gyro.core.resource.Output; import gyro.core.resource.Resource; import gyro.core.resource.Updatable; -import gyro.core.Type; -import gyro.core.resource.Output; - -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.compute.Snapshot; -import com.microsoft.azure.management.compute.SnapshotSkuType; -import com.microsoft.azure.management.compute.SnapshotStorageAccountTypes; -import com.microsoft.azure.management.compute.Snapshot.DefinitionStages.WithCreate; -import com.microsoft.azure.management.resources.fluentcore.arm.Region; import gyro.core.scope.State; import gyro.core.validation.Required; import gyro.core.validation.ValidStrings; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - /** * Creates a snapshot. * @@ -66,6 +64,7 @@ */ @Type("snapshot") public class SnapshotResource extends AzureResource implements Copyable { + private static final String SOURCE_DATA = "Data"; private static final String SOURCE_LINUX = "Linux"; private static final String SOURCE_WINDOWS = "Windows"; @@ -126,7 +125,7 @@ public void setName(String name) { * Determines what data type is used. */ @Required - @ValidStrings({"disk", "snapshot", "vhd"}) + @ValidStrings({ "disk", "snapshot", "vhd" }) public String getProvider() { return provider; } @@ -150,7 +149,7 @@ public void setResourceGroup(ResourceGroupResource resourceGroup) { /** * Specifies the sku type. */ - @ValidStrings({"Premium_LRS", "Standard_LRS", "Standard_ZRS"}) + @ValidStrings({ "Premium_LRS", "Standard_LRS", "Standard_ZRS" }) @Updatable public String getSku() { return sku; @@ -186,7 +185,7 @@ public void setSnapshot(SnapshotResource snapshot) { * The type of the disk, snapshot, or vhd used. */ @Required - @ValidStrings({"Linux", "Windows", "Data"}) + @ValidStrings({ "Linux", "Windows", "Data" }) public String getSource() { return source; } @@ -245,16 +244,16 @@ public void copyFrom(Snapshot snapshot) { setDisk(null); setSnapshot(null); if (snapshot.source().type().equals(CreationSourceType.COPIED_FROM_DISK)) { - setDisk(findById(DiskResource.class, snapshot.inner().creationData().sourceResourceId())); + setDisk(findById(DiskResource.class, snapshot.innerModel().creationData().sourceResourceId())); } else if (snapshot.source().type().equals(CreationSourceType.COPIED_FROM_SNAPSHOT)) { - setSnapshot(findById(SnapshotResource.class, snapshot.inner().creationData().sourceResourceId())); + setSnapshot(findById(SnapshotResource.class, snapshot.innerModel().creationData().sourceResourceId())); } - setCreationTime(snapshot.inner().timeCreated().toDate()); + setCreationTime(Date.from(snapshot.innerModel().timeCreated().toInstant())); } @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); Snapshot snapshot = client.snapshots().getById(getId()); @@ -269,13 +268,13 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); Snapshot.DefinitionStages.WithSnapshotSource withSnapshotSource = client.snapshots().define(getName()) - .withRegion(Region.fromName(getRegion())) - .withExistingResourceGroup(getResourceGroup().getName()); + .withRegion(Region.fromName(getRegion())) + .withExistingResourceGroup(getResourceGroup().getName()); - WithCreate withCreate = null; + Snapshot.DefinitionStages.WithCreate withCreate = null; boolean invalidSource = false; @@ -323,25 +322,25 @@ public void create(GyroUI ui, State state) { } Snapshot snapshot = withCreate.withTags(getTags()) - .create(); + .create(); copyFrom(snapshot); } @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); client.snapshots().getById(getId()) - .update() - .withSku(SnapshotSkuType.fromStorageAccountType(SnapshotStorageAccountTypes.fromString(getSku()))) - .withTags(getTags()) - .apply(); + .update() + .withSku(SnapshotSkuType.fromStorageAccountType(SnapshotStorageAccountTypes.fromString(getSku()))) + .withTags(getTags()) + .apply(); } @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); client.snapshots().deleteById(getId()); } diff --git a/src/main/java/gyro/azure/compute/VMScaleSetFinder.java b/src/main/java/gyro/azure/compute/VMScaleSetFinder.java index cfc20b61..e0e7a4ba 100644 --- a/src/main/java/gyro/azure/compute/VMScaleSetFinder.java +++ b/src/main/java/gyro/azure/compute/VMScaleSetFinder.java @@ -16,14 +16,15 @@ package gyro.azure.compute; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.compute.VirtualMachineScaleSet; -import gyro.azure.AzureFinder; -import gyro.core.Type; - import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; + +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.compute.models.VirtualMachineScaleSet; +import gyro.azure.AzureResourceManagerFinder; +import gyro.core.Type; /** * Query scale set. @@ -36,7 +37,8 @@ * scale-set: $(external-query azure::scale-set {}) */ @Type("scale-set") -public class VMScaleSetFinder extends AzureFinder { +public class VMScaleSetFinder extends AzureResourceManagerFinder { + private String id; /** @@ -51,12 +53,12 @@ public void setId(String id) { } @Override - protected List findAllAzure(Azure client) { - return client.virtualMachineScaleSets().list(); + protected List findAllAzure(AzureResourceManager client) { + return client.virtualMachineScaleSets().list().stream().collect(Collectors.toList()); } @Override - protected List findAzure(Azure client, Map filters) { + protected List findAzure(AzureResourceManager client, Map filters) { VirtualMachineScaleSet scaleSet = client.virtualMachineScaleSets().getById(filters.get("id")); if (scaleSet == null) { return Collections.emptyList(); diff --git a/src/main/java/gyro/azure/compute/VMScaleSetResource.java b/src/main/java/gyro/azure/compute/VMScaleSetResource.java index 2a2c44f6..6ae2665b 100644 --- a/src/main/java/gyro/azure/compute/VMScaleSetResource.java +++ b/src/main/java/gyro/azure/compute/VMScaleSetResource.java @@ -16,17 +16,26 @@ package gyro.azure.compute; -import com.microsoft.azure.PagedList; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.compute.CachingTypes; -import com.microsoft.azure.management.compute.KnownLinuxVirtualMachineImage; -import com.microsoft.azure.management.compute.KnownWindowsVirtualMachineImage; -import com.microsoft.azure.management.compute.ProximityPlacementGroupType; -import com.microsoft.azure.management.compute.VirtualMachineEvictionPolicyTypes; -import com.microsoft.azure.management.compute.VirtualMachineScaleSet; -import com.microsoft.azure.management.compute.VirtualMachineScaleSetSkuTypes; -import com.microsoft.azure.management.compute.VirtualMachineScaleSetVM; -import com.microsoft.azure.management.resources.fluentcore.arm.Region; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Base64; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.Region; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.compute.models.CachingTypes; +import com.azure.resourcemanager.compute.models.KnownLinuxVirtualMachineImage; +import com.azure.resourcemanager.compute.models.KnownWindowsVirtualMachineImage; +import com.azure.resourcemanager.compute.models.ProximityPlacementGroupType; +import com.azure.resourcemanager.compute.models.VirtualMachineEvictionPolicyTypes; +import com.azure.resourcemanager.compute.models.VirtualMachineScaleSet; +import com.azure.resourcemanager.compute.models.VirtualMachineScaleSetSkuTypes; +import com.azure.resourcemanager.compute.models.VirtualMachineScaleSetVM; import com.psddev.dari.util.ObjectUtils; import gyro.azure.AzureResource; import gyro.azure.Copyable; @@ -51,15 +60,6 @@ import gyro.core.validation.Required; import gyro.core.validation.ValidStrings; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Base64; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - /** * Creates a scale set. * @@ -118,6 +118,7 @@ */ @Type("scale-set") public class VMScaleSetResource extends AzureResource implements GyroInstances, Copyable { + private String name; private ResourceGroupResource resourceGroup; private String skuName; @@ -316,7 +317,7 @@ public void setPrimaryInternalLoadBalancer(LoadBalancerAttachment primaryInterna * The type of os for the VMs deployed by the Scale Set. */ @Required - @ValidStrings({"linux", "windows"}) + @ValidStrings({ "linux", "windows" }) public String getOsType() { return osType; } @@ -329,7 +330,7 @@ public void setOsType(String osType) { * The type of image to be used for the VMs deployed by the Scale Set. */ @Required - @ValidStrings({"latest", "popular", "specific", "custom", "stored"}) + @ValidStrings({ "latest", "popular", "specific", "custom", "stored" }) public String getImageType() { return imageType; } @@ -637,7 +638,7 @@ public void setEnableIpForwarding(Boolean enableIpForwarding) { /** * Set the OS Disk caching type for the VMs launched by this Scale Set. */ - @ValidStrings({"NONE", "READ_ONLY", "READ_WRITE"}) + @ValidStrings({ "NONE", "READ_ONLY", "READ_WRITE" }) public String getOsDiskCaching() { if (osDiskCaching != null) { osDiskCaching = osDiskCaching.toUpperCase(); @@ -694,7 +695,7 @@ public void setEnableLowPriorityVm(Boolean enableLowPriorityVm) { /** * Set the policy for eviction of the flagged low priority VMs launched by this Scale Set. Allowed only of 'enable-low-priority-vm' is set to ``true``. */ - @ValidStrings({"DEALLOCATE", "DELETE"}) + @ValidStrings({ "DEALLOCATE", "DELETE" }) public String getLowPriorityVmPolicy() { return lowPriorityVmPolicy; } @@ -772,7 +773,9 @@ public void setId(String id) { } private String getEncodedCustomData() { - return !ObjectUtils.isBlank(getCustomData()) ? Base64.getEncoder().encodeToString(getCustomData().getBytes()) : null; + return !ObjectUtils.isBlank(getCustomData()) + ? Base64.getEncoder().encodeToString(getCustomData().getBytes()) + : null; } private String getDecodedCustomData(String data) { @@ -789,11 +792,14 @@ public void copyFrom(VirtualMachineScaleSet scaleSet) { setSkuTier(scaleSet.sku().sku().tier()); setDoNotRunExtensionsOnOverprovisionedVMs(scaleSet.doNotRunExtensionsOnOverprovisionedVMs()); setApplicationGatewayBackendPoolIds(new HashSet<>(scaleSet.applicationGatewayBackendAddressPoolsIds())); - setApplicationSecurityGroups(scaleSet.applicationSecurityGroupIds().stream().map(o -> findById(ApplicationSecurityGroupResource.class, o)).collect(Collectors.toSet())); + setApplicationSecurityGroups(scaleSet.applicationSecurityGroupIds() + .stream() + .map(o -> findById(ApplicationSecurityGroupResource.class, o)) + .collect(Collectors.toSet())); setNetworkSecurityGroup(findById(NetworkSecurityGroupResource.class, scaleSet.networkSecurityGroupId())); setImagePublisher(scaleSet.storageProfile().imageReference().publisher()); - if (scaleSet.inner().proximityPlacementGroup() != null) { + if (scaleSet.innerModel().proximityPlacementGroup() != null) { setProximityPlacementGroup(newSubresource(ProximityPlacementGroupResource.class)); getProximityPlacementGroup().copyFrom(scaleSet.proximityPlacementGroup()); } else { @@ -810,7 +816,9 @@ public void copyFrom(VirtualMachineScaleSet scaleSet) { if (scaleSet.getPrimaryInternalLoadBalancer() != null) { LoadBalancerAttachment attachment = newSubresource(LoadBalancerAttachment.class); - attachment.setLoadBalancer(findById(LoadBalancerResource.class, scaleSet.getPrimaryInternalLoadBalancer().id())); + attachment.setLoadBalancer(findById( + LoadBalancerResource.class, + scaleSet.getPrimaryInternalLoadBalancer().id())); attachment.setBackends(scaleSet.listPrimaryInternalLoadBalancerBackends().keySet()); attachment.setInboundNatPools(scaleSet.listPrimaryInternalLoadBalancerInboundNatPools().keySet()); setPrimaryInternalLoadBalancer(attachment); @@ -820,7 +828,9 @@ public void copyFrom(VirtualMachineScaleSet scaleSet) { if (scaleSet.getPrimaryInternetFacingLoadBalancer() != null) { LoadBalancerAttachment attachment = newSubresource(LoadBalancerAttachment.class); - attachment.setLoadBalancer(findById(LoadBalancerResource.class, scaleSet.getPrimaryInternetFacingLoadBalancer().id())); + attachment.setLoadBalancer(findById( + LoadBalancerResource.class, + scaleSet.getPrimaryInternetFacingLoadBalancer().id())); attachment.setBackends(scaleSet.listPrimaryInternetFacingLoadBalancerBackends().keySet()); attachment.setInboundNatPools(scaleSet.listPrimaryInternetFacingLoadBalancerInboundNatPools().keySet()); setPrimaryInternetFacingLoadBalancer(attachment); @@ -848,11 +858,11 @@ public void copyFrom(VirtualMachineScaleSet scaleSet) { @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); VirtualMachineScaleSet scaleSet = client.virtualMachineScaleSets().getById(getId()); - if (scaleSet == null) { + if (scaleSet == null) { return false; } @@ -863,9 +873,10 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - Azure client = createClient(); - - VirtualMachineScaleSet.DefinitionStages.WithProximityPlacementGroup withProximityPlacementGroup = client.virtualMachineScaleSets().define(getName()) + AzureResourceManager client = createResourceManagerClient(); + + VirtualMachineScaleSet.DefinitionStages.WithProximityPlacementGroup withProximityPlacementGroup = client.virtualMachineScaleSets() + .define(getName()) .withRegion(Region.fromName(getRegion())) .withExistingResourceGroup(getResourceGroup().getName()) .withSku(VirtualMachineScaleSetSkuTypes.fromSkuNameAndTier(getSkuName(), getSkuTier())); @@ -874,7 +885,9 @@ public void create(GyroUI ui, State state) { if (getProximityPlacementGroup() != null) { primaryStage = withProximityPlacementGroup - .withNewProximityPlacementGroup(getProximityPlacementGroup().getName(), ProximityPlacementGroupType.fromString(getProximityPlacementGroup().getType())) + .withNewProximityPlacementGroup( + getProximityPlacementGroup().getName(), + ProximityPlacementGroupType.fromString(getProximityPlacementGroup().getType())) .withDoNotRunExtensionsOnOverprovisionedVMs(getDoNotRunExtensionsOnOverprovisionedVMs()) .withAdditionalCapabilities(getAdditionalCapability().toAdditionalCapabilities()) .withExistingPrimaryNetworkSubnet(client.networks().getById(getNetwork().getId()), getSubnetName()); @@ -890,9 +903,12 @@ public void create(GyroUI ui, State state) { if (getPrimaryInternetFacingLoadBalancer() == null) { internetFacingLbStage = primaryStage.withoutPrimaryInternetFacingLoadBalancer(); } else { - internetFacingLbStage = primaryStage.withExistingPrimaryInternetFacingLoadBalancer(client.loadBalancers().getById(getPrimaryInternetFacingLoadBalancer().getLoadBalancer().getId())) - .withPrimaryInternetFacingLoadBalancerBackends(getPrimaryInternetFacingLoadBalancer().getBackends().toArray(new String[0])) - .withPrimaryInternetFacingLoadBalancerInboundNatPools(getPrimaryInternetFacingLoadBalancer().getInboundNatPools().toArray(new String[0])); + internetFacingLbStage = primaryStage.withExistingPrimaryInternetFacingLoadBalancer(client.loadBalancers() + .getById(getPrimaryInternetFacingLoadBalancer().getLoadBalancer().getId())) + .withPrimaryInternetFacingLoadBalancerBackends(getPrimaryInternetFacingLoadBalancer().getBackends() + .toArray(new String[0])) + .withPrimaryInternetFacingLoadBalancerInboundNatPools(getPrimaryInternetFacingLoadBalancer().getInboundNatPools() + .toArray(new String[0])); } VirtualMachineScaleSet.DefinitionStages.WithOS internalLbStage; @@ -900,9 +916,12 @@ public void create(GyroUI ui, State state) { if (getPrimaryInternalLoadBalancer() == null) { internalLbStage = internetFacingLbStage.withoutPrimaryInternalLoadBalancer(); } else { - internalLbStage = internetFacingLbStage.withExistingPrimaryInternalLoadBalancer(client.loadBalancers().getById(getPrimaryInternalLoadBalancer().getLoadBalancer().getId())) - .withPrimaryInternalLoadBalancerBackends(getPrimaryInternalLoadBalancer().getBackends().toArray(new String[0])) - .withPrimaryInternalLoadBalancerInboundNatPools(getPrimaryInternalLoadBalancer().getInboundNatPools().toArray(new String[0])); + internalLbStage = internetFacingLbStage.withExistingPrimaryInternalLoadBalancer(client.loadBalancers() + .getById(getPrimaryInternalLoadBalancer().getLoadBalancer().getId())) + .withPrimaryInternalLoadBalancerBackends(getPrimaryInternalLoadBalancer().getBackends() + .toArray(new String[0])) + .withPrimaryInternalLoadBalancerInboundNatPools(getPrimaryInternalLoadBalancer().getInboundNatPools() + .toArray(new String[0])); } VirtualMachineScaleSet.DefinitionStages.WithCreate finalStage = null; @@ -915,13 +934,14 @@ public void create(GyroUI ui, State state) { if (getImageType().equals("latest")) { linuxStageA = internalLbStage.withLatestLinuxImage(getImagePublisher(), getImageOffer(), getImageSku()); } else if (getImageType().equals("popular")) { - linuxStageA = internalLbStage.withPopularLinuxImage(KnownLinuxVirtualMachineImage.valueOf(getKnownVirtualImage())); + linuxStageA = internalLbStage.withPopularLinuxImage(KnownLinuxVirtualMachineImage.valueOf( + getKnownVirtualImage())); } else if (getImageType().equals("specific")) { linuxStageA = internalLbStage.withSpecificLinuxImageVersion(client.virtualMachineImages() .getImage(getImageRegion(), getImagePublisher(), getImageOffer(), getImageSku(), getImageVersion()) .imageReference()); } else if (getImageType().equals("custom")) { - linuxStageB = internalLbStage.withLinuxCustomImage(getCustomImage()); + linuxStageB = internalLbStage.withGeneralizedLinuxCustomImage(getCustomImage()); } else { // stored linuxStageC = internalLbStage.withStoredLinuxImage(getStoredImage()); } @@ -929,7 +949,9 @@ public void create(GyroUI ui, State state) { // Todo Data Dsk and Os Disk if (linuxStageA != null) { if (!ObjectUtils.isBlank(getAdminPassword()) && !ObjectUtils.isBlank(getSsh())) { - finalStage = linuxStageA.withRootUsername(getAdminUserName()).withRootPassword(getAdminPassword()).withSsh(getSsh()); + finalStage = linuxStageA.withRootUsername(getAdminUserName()) + .withRootPassword(getAdminPassword()) + .withSsh(getSsh()); } else if (!ObjectUtils.isBlank(getAdminPassword())) { finalStage = linuxStageA.withRootUsername(getAdminUserName()).withRootPassword(getAdminPassword()); } else { @@ -937,7 +959,9 @@ public void create(GyroUI ui, State state) { } } else if (linuxStageB != null) { if (!ObjectUtils.isBlank(getAdminPassword()) && !ObjectUtils.isBlank(getSsh())) { - finalStage = linuxStageB.withRootUsername(getAdminUserName()).withRootPassword(getAdminPassword()).withSsh(getSsh()); + finalStage = linuxStageB.withRootUsername(getAdminUserName()) + .withRootPassword(getAdminPassword()) + .withSsh(getSsh()); } else if (!ObjectUtils.isBlank(getAdminPassword())) { finalStage = linuxStageB.withRootUsername(getAdminUserName()).withRootPassword(getAdminPassword()); } else { @@ -945,7 +969,9 @@ public void create(GyroUI ui, State state) { } } else { if (!ObjectUtils.isBlank(getAdminPassword()) && !ObjectUtils.isBlank(getSsh())) { - finalStage = linuxStageC.withRootUsername(getAdminUserName()).withRootPassword(getAdminPassword()).withSsh(getSsh()); + finalStage = linuxStageC.withRootUsername(getAdminUserName()) + .withRootPassword(getAdminPassword()) + .withSsh(getSsh()); } else if (!ObjectUtils.isBlank(getAdminPassword())) { finalStage = linuxStageC.withRootUsername(getAdminUserName()).withRootPassword(getAdminPassword()); } else { @@ -959,15 +985,19 @@ public void create(GyroUI ui, State state) { VirtualMachineScaleSet.DefinitionStages.WithWindowsAdminUsernameUnmanaged windowsStageC = null; if (getImageType().equals("latest")) { - windowsStageA = internalLbStage.withLatestWindowsImage(getImagePublisher(), getImageOffer(), getImageSku()); + windowsStageA = internalLbStage.withLatestWindowsImage( + getImagePublisher(), + getImageOffer(), + getImageSku()); } else if (getImageType().equals("popular")) { - windowsStageA = internalLbStage.withPopularWindowsImage(KnownWindowsVirtualMachineImage.valueOf(getKnownVirtualImage())); + windowsStageA = internalLbStage.withPopularWindowsImage(KnownWindowsVirtualMachineImage.valueOf( + getKnownVirtualImage())); } else if (getImageType().equals("specific")) { windowsStageA = internalLbStage.withSpecificWindowsImageVersion(client.virtualMachineImages() .getImage(getImageRegion(), getImagePublisher(), getImageOffer(), getImageSku(), getImageVersion()) .imageReference()); } else if (getImageType().equals("custom")) { - windowsStageB = internalLbStage.withWindowsCustomImage(getCustomImage()); + windowsStageB = internalLbStage.withGeneralizedWindowsCustomImage(getCustomImage()); } else { // stored windowsStageC = internalLbStage.withStoredWindowsImage(getStoredImage()); } @@ -976,11 +1006,15 @@ public void create(GyroUI ui, State state) { VirtualMachineScaleSet.DefinitionStages.WithWindowsCreateManaged windowsStageManaged = null; if (windowsStageA != null) { - windowsStageUnmanaged = windowsStageA.withAdminUsername(getAdminUserName()).withAdminPassword(getAdminPassword()).withUnmanagedDisks(); + windowsStageUnmanaged = windowsStageA.withAdminUsername(getAdminUserName()) + .withAdminPassword(getAdminPassword()) + .withUnmanagedDisks(); } else if (windowsStageB != null) { - windowsStageManaged = windowsStageB.withAdminUsername(getAdminUserName()).withAdminPassword(getAdminPassword()); + windowsStageManaged = windowsStageB.withAdminUsername(getAdminUserName()) + .withAdminPassword(getAdminPassword()); } else { - windowsStageUnmanaged = windowsStageC.withAdminUsername(getAdminUserName()).withAdminPassword(getAdminPassword()); + windowsStageUnmanaged = windowsStageC.withAdminUsername(getAdminUserName()) + .withAdminPassword(getAdminPassword()); } if (windowsStageUnmanaged != null) { @@ -1013,7 +1047,8 @@ public void create(GyroUI ui, State state) { } if (getStorageAccount() != null) { - finalStage = finalStage.withExistingStorageAccount(client.storageAccounts().getById(getStorageAccount().getId())); + finalStage = finalStage.withExistingStorageAccount(client.storageAccounts() + .getById(getStorageAccount().getId())); } finalStage = finalStage.withOverProvision(getEnableOverProvision()); @@ -1025,9 +1060,9 @@ public void create(GyroUI ui, State state) { if (getEnableBootDiagnostic()) { if (getBootDiagnosticBlob() != null) { finalStage = finalStage.withBootDiagnostics(getBootDiagnosticBlob().getUri()); - } - else if (getBootDiagnosticStorage() != null) { - finalStage = finalStage.withBootDiagnostics(client.storageAccounts().getById(getBootDiagnosticStorage().getId())); + } else if (getBootDiagnosticStorage() != null) { + finalStage = finalStage.withBootDiagnostics(client.storageAccounts() + .getById(getBootDiagnosticStorage().getId())); } else { finalStage = finalStage.withBootDiagnostics(); } @@ -1057,7 +1092,8 @@ else if (getBootDiagnosticStorage() != null) { if (getEnableLowPriorityVm()) { if (!ObjectUtils.isBlank(getLowPriorityVmPolicy())) { - finalStage = finalStage.withLowPriorityVirtualMachine(VirtualMachineEvictionPolicyTypes.fromString(getLowPriorityVmPolicy())); + finalStage = finalStage.withLowPriorityVirtualMachine(VirtualMachineEvictionPolicyTypes.fromString( + getLowPriorityVmPolicy())); } else { finalStage = finalStage.withLowPriorityVirtualMachine(); } @@ -1068,7 +1104,8 @@ else if (getBootDiagnosticStorage() != null) { } for (IdentityResource identity : getIdentities()) { - finalStage = finalStage.withExistingUserAssignedManagedServiceIdentity(client.identities().getById(identity.getId())); + finalStage = finalStage.withExistingUserAssignedManagedServiceIdentity(client.identities() + .getById(identity.getId())); } VirtualMachineScaleSet scaleSet = finalStage.create(); @@ -1077,7 +1114,7 @@ else if (getBootDiagnosticStorage() != null) { @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); VirtualMachineScaleSet scaleSet = client.virtualMachineScaleSets().getById(getId()); @@ -1085,20 +1122,31 @@ public void update(GyroUI ui, State state, Resource current, Set changed VirtualMachineScaleSet.UpdateStages.WithApply update; if (getPrimaryInternetFacingLoadBalancer() != null) { - a1 = scaleSet.update().withExistingPrimaryInternetFacingLoadBalancer(client.loadBalancers().getById(getPrimaryInternetFacingLoadBalancer().getLoadBalancer().getId())) - .withPrimaryInternetFacingLoadBalancerBackends(getPrimaryInternetFacingLoadBalancer().getBackends().toArray(new String[0])) - .withPrimaryInternetFacingLoadBalancerInboundNatPools(getPrimaryInternetFacingLoadBalancer().getInboundNatPools().toArray(new String[0])); + a1 = scaleSet.update() + .withExistingPrimaryInternetFacingLoadBalancer(client.loadBalancers() + .getById(getPrimaryInternetFacingLoadBalancer().getLoadBalancer().getId())) + .withPrimaryInternetFacingLoadBalancerBackends(getPrimaryInternetFacingLoadBalancer().getBackends() + .toArray(new String[0])) + .withPrimaryInternetFacingLoadBalancerInboundNatPools(getPrimaryInternetFacingLoadBalancer().getInboundNatPools() + .toArray(new String[0])); } if (getPrimaryInternalLoadBalancer() != null) { if (a1 != null) { - update = a1.withExistingPrimaryInternalLoadBalancer(client.loadBalancers().getById(getPrimaryInternalLoadBalancer().getLoadBalancer().getId())) - .withPrimaryInternalLoadBalancerBackends(getPrimaryInternalLoadBalancer().getBackends().toArray(new String[0])) - .withPrimaryInternalLoadBalancerInboundNatPools(getPrimaryInternalLoadBalancer().getInboundNatPools().toArray(new String[0])); + update = a1.withExistingPrimaryInternalLoadBalancer(client.loadBalancers() + .getById(getPrimaryInternalLoadBalancer().getLoadBalancer().getId())) + .withPrimaryInternalLoadBalancerBackends(getPrimaryInternalLoadBalancer().getBackends() + .toArray(new String[0])) + .withPrimaryInternalLoadBalancerInboundNatPools(getPrimaryInternalLoadBalancer().getInboundNatPools() + .toArray(new String[0])); } else { - update = scaleSet.update().withExistingPrimaryInternalLoadBalancer(client.loadBalancers().getById(getPrimaryInternalLoadBalancer().getLoadBalancer().getId())) - .withPrimaryInternalLoadBalancerBackends(getPrimaryInternalLoadBalancer().getBackends().toArray(new String[0])) - .withPrimaryInternalLoadBalancerInboundNatPools(getPrimaryInternalLoadBalancer().getInboundNatPools().toArray(new String[0])); + update = scaleSet.update() + .withExistingPrimaryInternalLoadBalancer(client.loadBalancers() + .getById(getPrimaryInternalLoadBalancer().getLoadBalancer().getId())) + .withPrimaryInternalLoadBalancerBackends(getPrimaryInternalLoadBalancer().getBackends() + .toArray(new String[0])) + .withPrimaryInternalLoadBalancerInboundNatPools(getPrimaryInternalLoadBalancer().getInboundNatPools() + .toArray(new String[0])); } } else { if (a1 != null) { @@ -1153,9 +1201,9 @@ public void update(GyroUI ui, State state, Resource current, Set changed if (getEnableBootDiagnostic()) { if (getBootDiagnosticBlob() != null) { update = update.withBootDiagnostics(getBootDiagnosticBlob().getUri()); - } - else if (getBootDiagnosticStorage() != null) { - update = update.withBootDiagnostics(client.storageAccounts().getById(getBootDiagnosticStorage().getId())); + } else if (getBootDiagnosticStorage() != null) { + update = update.withBootDiagnostics(client.storageAccounts() + .getById(getBootDiagnosticStorage().getId())); } else { update = update.withBootDiagnostics(); } @@ -1183,7 +1231,8 @@ else if (getBootDiagnosticStorage() != null) { } for (IdentityResource identity : getIdentities()) { - update = update.withExistingUserAssignedManagedServiceIdentity(client.identities().getById(identity.getId())); + update = update.withExistingUserAssignedManagedServiceIdentity(client.identities() + .getById(identity.getId())); } } @@ -1194,7 +1243,7 @@ else if (getBootDiagnosticStorage() != null) { @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); client.virtualMachineScaleSets().deleteById(getId()); } @@ -1202,13 +1251,12 @@ public void delete(GyroUI ui, State state) { @Override public List getInstances() { List instances = new ArrayList<>(); - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); VirtualMachineScaleSet virtualMachineScaleSet = client.virtualMachineScaleSets().getById(getId()); if (virtualMachineScaleSet != null) { - PagedList list = virtualMachineScaleSet.virtualMachines().list(); - list.loadAll(); + PagedIterable list = virtualMachineScaleSet.virtualMachines().list(); List instanceIds = list.stream() .map(VirtualMachineScaleSetVM::instanceId) .collect(Collectors.toList()); diff --git a/src/main/java/gyro/azure/compute/VMScaleSetScalingFinder.java b/src/main/java/gyro/azure/compute/VMScaleSetScalingFinder.java index 53ba1890..1b8564ae 100644 --- a/src/main/java/gyro/azure/compute/VMScaleSetScalingFinder.java +++ b/src/main/java/gyro/azure/compute/VMScaleSetScalingFinder.java @@ -16,14 +16,15 @@ package gyro.azure.compute; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.monitor.AutoscaleSetting; -import gyro.azure.AzureFinder; -import gyro.core.Type; - import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; + +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.monitor.models.AutoscaleSetting; +import gyro.azure.AzureResourceManagerFinder; +import gyro.core.Type; /** * Query scale set scaling. @@ -36,7 +37,8 @@ * scale-set-scaling: $(external-query azure::scale-set-scaling {}) */ @Type("scale-set-scaling") -public class VMScaleSetScalingFinder extends AzureFinder { +public class VMScaleSetScalingFinder extends AzureResourceManagerFinder { + private String id; /** @@ -51,12 +53,12 @@ public void setId(String id) { } @Override - protected List findAllAzure(Azure client) { - return client.autoscaleSettings().list(); + protected List findAllAzure(AzureResourceManager client) { + return client.autoscaleSettings().list().stream().collect(Collectors.toList()); } @Override - protected List findAzure(Azure client, Map filters) { + protected List findAzure(AzureResourceManager client, Map filters) { AutoscaleSetting setting = client.autoscaleSettings().getById(filters.get("id")); if (setting == null) { return Collections.emptyList(); diff --git a/src/main/java/gyro/azure/compute/VMScaleSetScalingResource.java b/src/main/java/gyro/azure/compute/VMScaleSetScalingResource.java index e6bc70f1..17a803cc 100644 --- a/src/main/java/gyro/azure/compute/VMScaleSetScalingResource.java +++ b/src/main/java/gyro/azure/compute/VMScaleSetScalingResource.java @@ -16,11 +16,18 @@ package gyro.azure.compute; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.monitor.AutoscaleProfile; -import com.microsoft.azure.management.monitor.AutoscaleSetting; -import com.microsoft.azure.management.monitor.ScaleRule; -import com.microsoft.azure.management.resources.fluentcore.arm.Region; +import java.time.ZoneOffset; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import com.azure.core.management.Region; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.monitor.models.AutoscaleProfile; +import com.azure.resourcemanager.monitor.models.AutoscaleSetting; +import com.azure.resourcemanager.monitor.models.ScaleRule; import com.psddev.dari.util.ObjectUtils; import gyro.azure.AzureResource; import gyro.azure.Copyable; @@ -35,12 +42,6 @@ import gyro.core.validation.Required; import org.joda.time.DateTime; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - /** * Creates a scale set. * @@ -313,7 +314,7 @@ public void copyFrom(AutoscaleSetting autoscaleSetting) { @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); AutoscaleSetting autoscaleSetting = client.autoscaleSettings().getById(getId()); @@ -328,7 +329,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); AutoscaleSetting.DefinitionStages.DefineAutoscaleSettingResourceProfiles basicStage = client.autoscaleSettings() .define(getName()) @@ -341,7 +342,7 @@ public void create(GyroUI ui, State state) { for (ScalingProfile profile : getProfile()) { AutoscaleProfile.DefinitionStages.Blank blankProfileStage = null; if (finalStage == null) { - blankProfileStage = basicStage.defineAutoscaleProfile(profile.getName()); + blankProfileStage = basicStage.defineAutoscaleProfile(profile.getName()); } else { blankProfileStage = finalStage.defineAutoscaleProfile(profile.getName()); } @@ -350,14 +351,27 @@ public void create(GyroUI ui, State state) { finalStage = blankProfileStage.withFixedInstanceCount(profile.getDefaultInstanceCount()).attach(); } else if (profile.getType().equals(ScalingProfile.ProfileType.FIXED_SCHEDULE)) { finalStage = blankProfileStage.withScheduleBasedScale(profile.getDefaultInstanceCount()) - .withFixedDateSchedule(profile.getFixedSchedule().getTimeZone(), new DateTime(profile.getFixedSchedule().getStartTime()), new DateTime(profile.getFixedSchedule().getEndTime())) + .withFixedDateSchedule( + profile.getFixedSchedule().getTimeZone(), + new DateTime(profile.getFixedSchedule().getStartTime()).toDate() + .toInstant() + .atOffset(ZoneOffset.UTC), + new DateTime(profile.getFixedSchedule().getEndTime()).toDate() + .toInstant() + .atOffset(ZoneOffset.UTC)) .attach(); } else if (profile.getType().equals(ScalingProfile.ProfileType.RECURRENT_SCHEDULE)) { finalStage = blankProfileStage.withScheduleBasedScale(profile.getDefaultInstanceCount()) - .withRecurrentSchedule(profile.getRecurrentSchedule().getTimeZone(), profile.getRecurrentSchedule().getStartTime(), profile.getRecurrentSchedule().toDayOfWeeks()) + .withRecurrentSchedule( + profile.getRecurrentSchedule().getTimeZone(), + profile.getRecurrentSchedule().getStartTime(), + profile.getRecurrentSchedule().toDayOfWeeks()) .attach(); } else { - AutoscaleProfile.DefinitionStages.WithScaleRule withScaleRule = blankProfileStage.withMetricBasedScale(profile.getMinInstanceCount(), profile.getMaxInstanceCount(), profile.getDefaultInstanceCount()); + AutoscaleProfile.DefinitionStages.WithScaleRule withScaleRule = blankProfileStage.withMetricBasedScale( + profile.getMinInstanceCount(), + profile.getMaxInstanceCount(), + profile.getDefaultInstanceCount()); AutoscaleProfile.DefinitionStages.WithScaleRuleOptional scaleRuleStage = null; for (ScalingRule rule : profile.getRule()) { ScaleRule.DefinitionStages.Blank blank; @@ -406,7 +420,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) throws Exception { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); AutoscaleSetting autoscaleSetting = client.autoscaleSettings().getById(getId()); @@ -444,7 +458,9 @@ public void update(GyroUI ui, State state, Resource current, Set changed if (changedFieldNames.contains("profile")) { for (ScalingProfile profile : ((VMScaleSetScalingResource) current).getProfile()) { - if (getProfile().stream().noneMatch(o -> o.getName().equals(profile.getName()) && o.getType().equals(profile.getType()) && o.getType().equals(ScalingProfile.ProfileType.FIXED))) { + if (getProfile().stream() + .noneMatch(o -> o.getName().equals(profile.getName()) && o.getType().equals(profile.getType()) + && o.getType().equals(ScalingProfile.ProfileType.FIXED))) { update = update.withoutAutoscaleProfile(profile.getName()); } } @@ -458,15 +474,28 @@ public void update(GyroUI ui, State state, Resource current, Set changed if (profile.getType().equals(ScalingProfile.ProfileType.FIXED_SCHEDULE)) { update = profileStage .withScheduleBasedScale(profile.getDefaultInstanceCount()) - .withFixedDateSchedule(profile.getFixedSchedule().getTimeZone(), new DateTime(profile.getFixedSchedule().getStartTime()), new DateTime(profile.getFixedSchedule().getEndTime())) + .withFixedDateSchedule( + profile.getFixedSchedule().getTimeZone(), + new DateTime(profile.getFixedSchedule().getStartTime()).toDate() + .toInstant() + .atOffset(ZoneOffset.UTC), + new DateTime(profile.getFixedSchedule().getEndTime()).toDate() + .toInstant() + .atOffset(ZoneOffset.UTC)) .attach(); } else if (profile.getType().equals(ScalingProfile.ProfileType.RECURRENT_SCHEDULE)) { update = profileStage .withScheduleBasedScale(profile.getDefaultInstanceCount()) - .withRecurrentSchedule(profile.getRecurrentSchedule().getTimeZone(), profile.getRecurrentSchedule().getStartTime(), profile.getRecurrentSchedule().toDayOfWeeks()) + .withRecurrentSchedule( + profile.getRecurrentSchedule().getTimeZone(), + profile.getRecurrentSchedule().getStartTime(), + profile.getRecurrentSchedule().toDayOfWeeks()) .attach(); } else { - AutoscaleProfile.UpdateDefinitionStages.WithScaleRule withScaleRule = profileStage.withMetricBasedScale(profile.getMinInstanceCount(), profile.getMaxInstanceCount(), profile.getDefaultInstanceCount()); + AutoscaleProfile.UpdateDefinitionStages.WithScaleRule withScaleRule = profileStage.withMetricBasedScale( + profile.getMinInstanceCount(), + profile.getMaxInstanceCount(), + profile.getDefaultInstanceCount()); AutoscaleProfile.UpdateDefinitionStages.WithScaleRuleOptional scaleRuleStage = null; for (ScalingRule rule : profile.getRule()) { if (scaleRuleStage == null) { @@ -486,7 +515,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); client.autoscaleSettings().deleteById(getId()); } diff --git a/src/main/java/gyro/azure/compute/VMScaleSetVirtualMachine.java b/src/main/java/gyro/azure/compute/VMScaleSetVirtualMachine.java index 360d40b0..2cc8facd 100644 --- a/src/main/java/gyro/azure/compute/VMScaleSetVirtualMachine.java +++ b/src/main/java/gyro/azure/compute/VMScaleSetVirtualMachine.java @@ -2,8 +2,8 @@ import java.util.Collection; -import com.microsoft.azure.management.compute.VirtualMachineScaleSetVM; -import com.microsoft.azure.management.network.implementation.NetworkInterfaceIPConfigurationInner; +import com.azure.resourcemanager.compute.models.VirtualMachineScaleSetVM; +import com.azure.resourcemanager.network.fluent.models.NetworkInterfaceIpConfigurationInner; import gyro.azure.Copyable; import gyro.core.GyroInstance; import gyro.core.resource.Diffable; @@ -70,20 +70,20 @@ public void copyFrom(VirtualMachineScaleSetVM model) { setName(model.computerName()); setInstanceId(model.instanceId()); setState(model.powerState().toString()); - setLocation(model.inner().location()); + setLocation(model.innerModel().location()); //model - NetworkInterfaceIPConfigurationInner ipConfig = model.listNetworkInterfaces() + NetworkInterfaceIpConfigurationInner ipConfig = model.listNetworkInterfaces() .stream() .filter(nic -> nic.name().equals("primary-nic-cfg")) - .map(nic -> nic.inner().ipConfigurations()) + .map(nic -> nic.innerModel().ipConfigurations()) .flatMap(Collection::stream) - .filter(NetworkInterfaceIPConfigurationInner::primary) + .filter(NetworkInterfaceIpConfigurationInner::primary) .findFirst() .orElse(null); if (ipConfig != null) { - setPrivateIp(ipConfig.privateIPAddress()); - setPublicIp(ipConfig.publicIPAddress() != null ? ipConfig.publicIPAddress().ipAddress() : null); + setPrivateIp(ipConfig.privateIpAddress()); + setPublicIp(ipConfig.publicIpAddress() != null ? ipConfig.publicIpAddress().ipAddress() : null); } } @@ -110,7 +110,9 @@ public String getGyroInstancePublicIpAddress() { @Override public String getGyroInstanceHostname() { - return getGyroInstancePublicIpAddress() != null ? getGyroInstancePublicIpAddress() : getGyroInstancePrivateIpAddress(); + return getGyroInstancePublicIpAddress() != null + ? getGyroInstancePublicIpAddress() + : getGyroInstancePrivateIpAddress(); } @Override diff --git a/src/main/java/gyro/azure/compute/VirtualMachineFinder.java b/src/main/java/gyro/azure/compute/VirtualMachineFinder.java index 74892b56..1edf5e92 100644 --- a/src/main/java/gyro/azure/compute/VirtualMachineFinder.java +++ b/src/main/java/gyro/azure/compute/VirtualMachineFinder.java @@ -16,14 +16,15 @@ package gyro.azure.compute; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.compute.VirtualMachine; -import gyro.azure.AzureFinder; -import gyro.core.Type; - import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; + +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.compute.models.VirtualMachine; +import gyro.azure.AzureResourceManagerFinder; +import gyro.core.Type; /** * Query virtual machine. @@ -36,7 +37,8 @@ * virtual-machine: $(external-query azure::virtual-machine {}) */ @Type("virtual-machine") -public class VirtualMachineFinder extends AzureFinder { +public class VirtualMachineFinder extends AzureResourceManagerFinder { + private String id; /** @@ -49,13 +51,14 @@ public String getId() { public void setId(String id) { this.id = id; } + @Override - protected List findAllAzure(Azure client) { - return client.virtualMachines().list(); + protected List findAllAzure(AzureResourceManager client) { + return client.virtualMachines().list().stream().collect(Collectors.toList()); } @Override - protected List findAzure(Azure client, Map filters) { + protected List findAzure(AzureResourceManager client, Map filters) { VirtualMachine virtualMachine = client.virtualMachines().getById(filters.get("id")); if (virtualMachine == null) { diff --git a/src/main/java/gyro/azure/compute/VirtualMachineImageFinder.java b/src/main/java/gyro/azure/compute/VirtualMachineImageFinder.java index c982785b..f2c15541 100644 --- a/src/main/java/gyro/azure/compute/VirtualMachineImageFinder.java +++ b/src/main/java/gyro/azure/compute/VirtualMachineImageFinder.java @@ -16,14 +16,15 @@ package gyro.azure.compute; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.compute.VirtualMachineCustomImage; -import gyro.azure.AzureFinder; -import gyro.core.Type; - import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; + +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.compute.models.VirtualMachineCustomImage; +import gyro.azure.AzureResourceManagerFinder; +import gyro.core.Type; /** * Query virtual machine image. @@ -36,7 +37,9 @@ * virtual-machine-image: $(external-query azure::virtual-machine-image {}) */ @Type("virtual-machine-image") -public class VirtualMachineImageFinder extends AzureFinder { +public class VirtualMachineImageFinder + extends AzureResourceManagerFinder { + private String id; /** @@ -51,12 +54,12 @@ public void setId(String id) { } @Override - protected List findAllAzure(Azure client) { - return client.virtualMachineCustomImages().list(); + protected List findAllAzure(AzureResourceManager client) { + return client.virtualMachineCustomImages().list().stream().collect(Collectors.toList()); } @Override - protected List findAzure(Azure client, Map filters) { + protected List findAzure(AzureResourceManager client, Map filters) { VirtualMachineCustomImage image = client.virtualMachineCustomImages().getById(filters.get("id")); if (image == null) { diff --git a/src/main/java/gyro/azure/compute/VirtualMachineImageResource.java b/src/main/java/gyro/azure/compute/VirtualMachineImageResource.java index 9cce62e9..bac03722 100644 --- a/src/main/java/gyro/azure/compute/VirtualMachineImageResource.java +++ b/src/main/java/gyro/azure/compute/VirtualMachineImageResource.java @@ -16,10 +16,14 @@ package gyro.azure.compute; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.compute.HyperVGenerationTypes; -import com.microsoft.azure.management.compute.VirtualMachineCustomImage; -import com.microsoft.azure.management.resources.fluentcore.arm.Region; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import com.azure.core.management.Region; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.compute.models.HyperVGenerationTypes; +import com.azure.resourcemanager.compute.models.VirtualMachineCustomImage; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.azure.resources.ResourceGroupResource; @@ -32,10 +36,6 @@ import gyro.core.validation.Required; import gyro.core.validation.ValidStrings; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - /** * Creates a virtual machine image * @@ -52,6 +52,7 @@ */ @Type("virtual-machine-image") public class VirtualMachineImageResource extends AzureResource implements Copyable { + private String name; private ResourceGroupResource resourceGroup; private VirtualMachineResource virtualMachine; @@ -99,7 +100,7 @@ public void setVirtualMachine(VirtualMachineResource virtualMachine) { /** * The Hyper V Generation for the virtual machine image. Defaults to ``V1``. */ - @ValidStrings({"V1", "V2"}) + @ValidStrings({ "V1", "V2" }) public String getHyperVGeneration() { if (hyperVGeneration == null) { hyperVGeneration = "V1"; @@ -124,7 +125,7 @@ public Map getTags() { } public void setTags(Map tags) { - this.tags = tags; + this.tags = tags; } /** @@ -158,7 +159,9 @@ public void setId(String id) { @Override public void copyFrom(VirtualMachineCustomImage image) { setHyperVGeneration(image.hyperVGeneration().toString()); - setVirtualMachine(image.isCreatedFromVirtualMachine() ? findById(VirtualMachineResource.class, image.sourceVirtualMachineId()) : null); + setVirtualMachine(image.isCreatedFromVirtualMachine() ? findById( + VirtualMachineResource.class, + image.sourceVirtualMachineId()) : null); setId(image.id()); setName(image.name()); setResourceGroup(findById(ResourceGroupResource.class, image.resourceGroupName())); @@ -167,7 +170,7 @@ public void copyFrom(VirtualMachineCustomImage image) { @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); VirtualMachineCustomImage image = client.virtualMachineCustomImages().getById(getId()); @@ -182,7 +185,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) throws Exception { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); VirtualMachineCustomImage.DefinitionStages.WithCreate withCreate = client.virtualMachineCustomImages() .define(getName()) @@ -211,7 +214,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) throws Exception { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); client.virtualMachineCustomImages().deleteById(getId()); } diff --git a/src/main/java/gyro/azure/compute/VirtualMachineResource.java b/src/main/java/gyro/azure/compute/VirtualMachineResource.java index fc89f536..1c917fbe 100644 --- a/src/main/java/gyro/azure/compute/VirtualMachineResource.java +++ b/src/main/java/gyro/azure/compute/VirtualMachineResource.java @@ -16,49 +16,57 @@ package gyro.azure.compute; -import com.microsoft.azure.SubResource; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.compute.AvailabilitySets; -import com.microsoft.azure.management.compute.CachingTypes; -import com.microsoft.azure.management.compute.Disk; -import com.microsoft.azure.management.compute.InstanceViewStatus; -import com.microsoft.azure.management.compute.KnownLinuxVirtualMachineImage; -import com.microsoft.azure.management.compute.KnownWindowsVirtualMachineImage; -import com.microsoft.azure.management.compute.NetworkInterfaceReference; -import com.microsoft.azure.management.compute.OperatingSystemTypes; -import com.microsoft.azure.management.compute.StorageAccountTypes; -import com.microsoft.azure.management.compute.VirtualMachine; -import com.microsoft.azure.management.compute.VirtualMachine.DefinitionStages.WithCreate; -import com.microsoft.azure.management.compute.VirtualMachine.DefinitionStages.WithLinuxCreateManaged; -import com.microsoft.azure.management.compute.VirtualMachine.DefinitionStages.WithLinuxCreateManagedOrUnmanaged; -import com.microsoft.azure.management.compute.VirtualMachine.DefinitionStages.WithLinuxCreateUnmanaged; -import com.microsoft.azure.management.compute.VirtualMachine.DefinitionStages.WithLinuxRootPasswordOrPublicKeyManaged; -import com.microsoft.azure.management.compute.VirtualMachine.DefinitionStages.WithLinuxRootPasswordOrPublicKeyManagedOrUnmanaged; -import com.microsoft.azure.management.compute.VirtualMachine.DefinitionStages.WithLinuxRootPasswordOrPublicKeyUnmanaged; -import com.microsoft.azure.management.compute.VirtualMachine.DefinitionStages.WithLinuxRootUsernameManaged; -import com.microsoft.azure.management.compute.VirtualMachine.DefinitionStages.WithLinuxRootUsernameManagedOrUnmanaged; -import com.microsoft.azure.management.compute.VirtualMachine.DefinitionStages.WithLinuxRootUsernameUnmanaged; -import com.microsoft.azure.management.compute.VirtualMachine.DefinitionStages.WithManagedCreate; -import com.microsoft.azure.management.compute.VirtualMachine.DefinitionStages.WithUnmanagedCreate; -import com.microsoft.azure.management.compute.VirtualMachine.DefinitionStages.WithFromImageCreateOptionsManaged; -import com.microsoft.azure.management.compute.VirtualMachine.DefinitionStages.WithFromImageCreateOptionsManagedOrUnmanaged; -import com.microsoft.azure.management.compute.VirtualMachine.DefinitionStages.WithFromImageCreateOptionsUnmanaged; -import com.microsoft.azure.management.compute.VirtualMachine.DefinitionStages.WithNetwork; -import com.microsoft.azure.management.compute.VirtualMachine.DefinitionStages.WithOS; -import com.microsoft.azure.management.compute.VirtualMachine.DefinitionStages.WithPrivateIP; -import com.microsoft.azure.management.compute.VirtualMachine.DefinitionStages.WithPublicIPAddress; -import com.microsoft.azure.management.compute.VirtualMachine.DefinitionStages.WithWindowsAdminUsernameManaged; -import com.microsoft.azure.management.compute.VirtualMachine.DefinitionStages.WithWindowsAdminUsernameManagedOrUnmanaged; -import com.microsoft.azure.management.compute.VirtualMachine.DefinitionStages.WithWindowsAdminUsernameUnmanaged; -import com.microsoft.azure.management.compute.VirtualMachine.DefinitionStages.WithWindowsCreateManaged; -import com.microsoft.azure.management.compute.VirtualMachine.DefinitionStages.WithWindowsCreateManagedOrUnmanaged; -import com.microsoft.azure.management.compute.VirtualMachine.DefinitionStages.WithWindowsCreateUnmanaged; -import com.microsoft.azure.management.compute.VirtualMachineDataDisk; -import com.microsoft.azure.management.compute.VirtualMachineSizeTypes; -import com.microsoft.azure.management.resources.fluentcore.arm.Region; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import com.azure.core.management.Region; +import com.azure.core.management.SubResource; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.compute.models.CachingTypes; +import com.azure.resourcemanager.compute.models.Disk; +import com.azure.resourcemanager.compute.models.InstanceViewStatus; +import com.azure.resourcemanager.compute.models.KnownLinuxVirtualMachineImage; +import com.azure.resourcemanager.compute.models.KnownWindowsVirtualMachineImage; +import com.azure.resourcemanager.compute.models.NetworkInterfaceReference; +import com.azure.resourcemanager.compute.models.OperatingSystemTypes; +import com.azure.resourcemanager.compute.models.StorageAccountTypes; +import com.azure.resourcemanager.compute.models.VirtualMachine; +import com.azure.resourcemanager.compute.models.VirtualMachine.DefinitionStages.WithCreate; +import com.azure.resourcemanager.compute.models.VirtualMachine.DefinitionStages.WithFromImageCreateOptionsManaged; +import com.azure.resourcemanager.compute.models.VirtualMachine.DefinitionStages.WithFromImageCreateOptionsManagedOrUnmanaged; +import com.azure.resourcemanager.compute.models.VirtualMachine.DefinitionStages.WithFromImageCreateOptionsUnmanaged; +import com.azure.resourcemanager.compute.models.VirtualMachine.DefinitionStages.WithLinuxCreateManaged; +import com.azure.resourcemanager.compute.models.VirtualMachine.DefinitionStages.WithLinuxCreateManagedOrUnmanaged; +import com.azure.resourcemanager.compute.models.VirtualMachine.DefinitionStages.WithLinuxCreateUnmanaged; +import com.azure.resourcemanager.compute.models.VirtualMachine.DefinitionStages.WithLinuxRootPasswordOrPublicKeyManaged; +import com.azure.resourcemanager.compute.models.VirtualMachine.DefinitionStages.WithLinuxRootPasswordOrPublicKeyManagedOrUnmanaged; +import com.azure.resourcemanager.compute.models.VirtualMachine.DefinitionStages.WithLinuxRootPasswordOrPublicKeyUnmanaged; +import com.azure.resourcemanager.compute.models.VirtualMachine.DefinitionStages.WithLinuxRootUsernameManaged; +import com.azure.resourcemanager.compute.models.VirtualMachine.DefinitionStages.WithLinuxRootUsernameManagedOrUnmanaged; +import com.azure.resourcemanager.compute.models.VirtualMachine.DefinitionStages.WithLinuxRootUsernameUnmanaged; +import com.azure.resourcemanager.compute.models.VirtualMachine.DefinitionStages.WithManagedCreate; +import com.azure.resourcemanager.compute.models.VirtualMachine.DefinitionStages.WithNetwork; +import com.azure.resourcemanager.compute.models.VirtualMachine.DefinitionStages.WithOS; +import com.azure.resourcemanager.compute.models.VirtualMachine.DefinitionStages.WithPrivateIP; +import com.azure.resourcemanager.compute.models.VirtualMachine.DefinitionStages.WithPublicIPAddress; +import com.azure.resourcemanager.compute.models.VirtualMachine.DefinitionStages.WithWindowsAdminUsernameManaged; +import com.azure.resourcemanager.compute.models.VirtualMachine.DefinitionStages.WithWindowsAdminUsernameManagedOrUnmanaged; +import com.azure.resourcemanager.compute.models.VirtualMachine.DefinitionStages.WithWindowsAdminUsernameUnmanaged; +import com.azure.resourcemanager.compute.models.VirtualMachine.DefinitionStages.WithWindowsCreateManaged; +import com.azure.resourcemanager.compute.models.VirtualMachine.DefinitionStages.WithWindowsCreateManagedOrUnmanaged; +import com.azure.resourcemanager.compute.models.VirtualMachine.DefinitionStages.WithWindowsCreateUnmanaged; +import com.azure.resourcemanager.compute.models.VirtualMachineDataDisk; +import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes; import com.psddev.dari.util.ObjectUtils; import com.psddev.dari.util.StringUtils; - import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.azure.identity.IdentityResource; @@ -69,29 +77,17 @@ import gyro.core.GyroException; import gyro.core.GyroInstance; import gyro.core.GyroUI; +import gyro.core.Type; import gyro.core.resource.DiffableInternals; import gyro.core.resource.Id; -import gyro.core.resource.Updatable; -import gyro.core.Type; import gyro.core.resource.Output; import gyro.core.resource.Resource; +import gyro.core.resource.Updatable; import gyro.core.scope.State; import gyro.core.validation.Required; import gyro.core.validation.ValidStrings; import gyro.core.validation.ValidationError; -import java.util.ArrayList; -import java.util.Base64; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.stream.Collectors; - /** * Creates a virtual machine. * @@ -126,6 +122,7 @@ */ @Type("virtual-machine") public class VirtualMachineResource extends AzureResource implements GyroInstance, Copyable { + private String name; private ResourceGroupResource resourceGroup; private NetworkResource network; @@ -301,7 +298,7 @@ public void setPrivateIpAddress(String privateIpAddress) { * The os for the Virtual Machine. */ @Required - @ValidStrings({"linux", "windows"}) + @ValidStrings({ "linux", "windows" }) public String getOsType() { return osType != null ? osType.toLowerCase() : null; } @@ -327,8 +324,8 @@ public void setOsDisk(DiskResource osDisk) { @Updatable public Boolean getDeleteOsDiskOnTerminate() { return deleteOsDiskOnTerminate == null - ? deleteOsDiskOnTerminate = Boolean.FALSE - : deleteOsDiskOnTerminate; + ? deleteOsDiskOnTerminate = Boolean.FALSE + : deleteOsDiskOnTerminate; } public void setDeleteOsDiskOnTerminate(Boolean deleteOsDiskOnTerminate) { @@ -341,8 +338,8 @@ public void setDeleteOsDiskOnTerminate(Boolean deleteOsDiskOnTerminate) { @Updatable public Set getDataDisks() { return dataDisks == null - ? dataDisks = new LinkedHashSet<>() - : dataDisks; + ? dataDisks = new LinkedHashSet<>() + : dataDisks; } public void setDataDisks(Set dataDisks) { @@ -364,7 +361,7 @@ public void setSubnet(String subnet) { * Type of Virtual Machine image. Defaults to specialized. */ @Required - @ValidStrings({"popular", "specialized", "latest", "specific", "custom", "gallery"}) + @ValidStrings({ "popular", "specialized", "latest", "specific", "custom", "gallery" }) public String getVmImageType() { if (vmImageType == null) { vmImageType = "specialized"; @@ -436,7 +433,7 @@ public void setCachingType(String cachingType) { /** * The data disk storage account type for the Virtual Machine. */ - @ValidStrings({"STANDARD_LRS", "PREMIUM_LRS", "STANDARDSSD_LRS"}) + @ValidStrings({ "STANDARD_LRS", "PREMIUM_LRS", "STANDARDSSD_LRS" }) @Updatable public String getStorageAccountTypeDataDisk() { return storageAccountTypeDataDisk; @@ -449,7 +446,7 @@ public void setStorageAccountTypeDataDisk(String storageAccountTypeDataDisk) { /** * The os disk storage account type for the Virtual Machine. */ - @ValidStrings({"STANDARD_LRS", "PREMIUM_LRS", "STANDARDSSD_LRS"}) + @ValidStrings({ "STANDARD_LRS", "PREMIUM_LRS", "STANDARDSSD_LRS" }) public String getStorageAccountTypeOsDisk() { return storageAccountTypeOsDisk; } @@ -700,27 +697,32 @@ public void copyFrom(VirtualMachine virtualMachine) { setId(virtualMachine.id()); setVmId(virtualMachine.vmId()); - setAvailabilitySet(virtualMachine.availabilitySetId() != null ? findById(AvailabilitySetResource.class, virtualMachine.availabilitySetId()) : null); - setPublicIpAddress(virtualMachine.getPrimaryPublicIPAddressId() != null ? findById(PublicIpAddressResource.class, virtualMachine.getPrimaryPublicIPAddressId()) : null); + setAvailabilitySet(virtualMachine.availabilitySetId() != null ? findById( + AvailabilitySetResource.class, + virtualMachine.availabilitySetId()) : null); + setPublicIpAddress(virtualMachine.getPrimaryPublicIPAddressId() != null ? findById( + PublicIpAddressResource.class, + virtualMachine.getPrimaryPublicIPAddressId()) : null); setOsType(virtualMachine.osType().name()); setNetworkInterface( - findById(NetworkInterfaceResource.class, - virtualMachine.inner().networkProfile() + findById( + NetworkInterfaceResource.class, + virtualMachine.innerModel().networkProfile() .networkInterfaces().stream() .filter(NetworkInterfaceReference::primary).findFirst() .map(SubResource::id).orElse(null) ) ); setSecondaryNetworkInterface( - virtualMachine.inner().networkProfile() + virtualMachine.innerModel().networkProfile() .networkInterfaces().stream() .filter(o -> !o.primary()) .map(o -> findById(NetworkInterfaceResource.class, o.id())) .collect(Collectors.toSet()) ); - setVmSizeType(virtualMachine.inner().hardwareProfile().vmSize().toString()); + setVmSizeType(virtualMachine.innerModel().hardwareProfile().vmSize().toString()); Set dataDisks = new LinkedHashSet<>(); Map dataDiskMap = virtualMachine.dataDisks(); @@ -749,19 +751,26 @@ public void copyFrom(VirtualMachine virtualMachine) { } setState(virtualMachine.powerState().toString()); - setLocation(virtualMachine.inner().location()); + setLocation(virtualMachine.innerModel().location()); setComputerName(virtualMachine.computerName()); - setPublicIpAddressIp(virtualMachine.getPrimaryPublicIPAddress()!= null ? virtualMachine.getPrimaryPublicIPAddress().ipAddress() : null); - InstanceViewStatus instanceViewStatus = virtualMachine.instanceView().statuses().stream().filter(o -> o.code().equals("ProvisioningState/succeeded")).findFirst().orElse(null); - setLaunchDate(instanceViewStatus != null ? instanceViewStatus.time().toDate() : null); - - Azure client = createClient(); + setPublicIpAddressIp(virtualMachine.getPrimaryPublicIPAddress() != null + ? virtualMachine.getPrimaryPublicIPAddress().ipAddress() + : null); + InstanceViewStatus instanceViewStatus = virtualMachine.instanceView() + .statuses() + .stream() + .filter(o -> o.code().equals("ProvisioningState/succeeded")) + .findFirst() + .orElse(null); + setLaunchDate(instanceViewStatus != null ? Date.from(instanceViewStatus.time().toInstant()) : null); + + AzureResourceManager client = createResourceManagerClient(); setPrivateIpAddress(client.networkInterfaces().getById(getNetworkInterface().getId()).primaryPrivateIP()); } @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); VirtualMachine virtualMachine = client.virtualMachines().getById(getId()); @@ -776,7 +785,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - VirtualMachine virtualMachine = doVMFluentWorkflow(createClient()).create(); + VirtualMachine virtualMachine = doVMFluentWorkflow(createResourceManagerClient()).create(); setId(virtualMachine.id()); setVmId(virtualMachine.vmId()); copyFrom(virtualMachine); @@ -792,7 +801,7 @@ public void create(GyroUI ui, State state) { * Configure Generic Host attributes * @return {@link WithCreate} VM Definition object ready for creation */ - private WithCreate doVMFluentWorkflow(Azure client) { + private WithCreate doVMFluentWorkflow(AzureResourceManager client) { WithNetwork initialVMBuilder = configureRegionAndResourceGroups(client.virtualMachines().define(getName())); WithOS networkConfigured = configureNetwork(client, initialVMBuilder); WithCreate osConfiguredVMBuilder = configureOS(client, networkConfigured); @@ -810,7 +819,8 @@ private WithCreate doVMFluentWorkflow(Azure client) { } if (getAvailabilitySet() != null) { - osConfiguredVMBuilder = osConfiguredVMBuilder.withExistingAvailabilitySet(client.availabilitySets().getById(getAvailabilitySet().getId())); + osConfiguredVMBuilder = osConfiguredVMBuilder.withExistingAvailabilitySet(client.availabilitySets() + .getById(getAvailabilitySet().getId())); } if (getEnableSystemManagedServiceIdentity()) { @@ -818,12 +828,13 @@ private WithCreate doVMFluentWorkflow(Azure client) { } for (IdentityResource identity : getIdentities()) { - osConfiguredVMBuilder = osConfiguredVMBuilder.withExistingUserAssignedManagedServiceIdentity(client.identities().getById(identity.getId())); + osConfiguredVMBuilder = osConfiguredVMBuilder.withExistingUserAssignedManagedServiceIdentity(client.identities() + .getById(identity.getId())); } return osConfiguredVMBuilder - .withSize(getVmSizeType()) - .withTags(getTags()); + .withSize(getVmSizeType()) + .withTags(getTags()); } /** @@ -833,7 +844,7 @@ private WithCreate doVMFluentWorkflow(Azure client) { */ private WithNetwork configureRegionAndResourceGroups(VirtualMachine.DefinitionStages.Blank initialVMBuilder) { return initialVMBuilder.withRegion(Region.fromName(getRegion())) - .withExistingResourceGroup(getResourceGroup().getName()); + .withExistingResourceGroup(getResourceGroup().getName()); } /** @@ -842,20 +853,20 @@ private WithNetwork configureRegionAndResourceGroups(VirtualMachine.DefinitionSt * creates one with either a defined or generated private and public IP. * @return {@link WithOS} VM Definition object ready for OS configurations */ - private WithOS configureNetwork(Azure client, WithNetwork initialVMBuilder) { + private WithOS configureNetwork(AzureResourceManager client, WithNetwork initialVMBuilder) { WithOS networkConfigured; if (!ObjectUtils.isBlank(getNetworkInterface())) { networkConfigured = initialVMBuilder.withExistingPrimaryNetworkInterface( - client.networkInterfaces().getByResourceGroup( - getResourceGroup().getName(), getNetworkInterface().getName() - )); + client.networkInterfaces().getByResourceGroup( + getResourceGroup().getName(), getNetworkInterface().getName() + )); } else { WithPrivateIP withPrivateIP = initialVMBuilder - .withExistingPrimaryNetwork(client.networks().getById(getNetwork().getId())) - .withSubnet(getSubnet()); + .withExistingPrimaryNetwork(client.networks().getById(getNetwork().getId())) + .withSubnet(getSubnet()); WithPublicIPAddress withPublicIpAddress; if (!ObjectUtils.isBlank(getPrivateIpAddress())) { @@ -866,7 +877,8 @@ private WithOS configureNetwork(Azure client, WithNetwork initialVMBuilder) { if (!ObjectUtils.isBlank(getPublicIpAddress())) { networkConfigured = withPublicIpAddress.withExistingPrimaryPublicIPAddress( - client.publicIPAddresses().getByResourceGroup(getResourceGroup().getName(), getPublicIpAddress().getName()) + client.publicIpAddresses() + .getByResourceGroup(getResourceGroup().getName(), getPublicIpAddress().getName()) ); } else { networkConfigured = withPublicIpAddress.withoutPrimaryPublicIPAddress(); @@ -882,8 +894,8 @@ private WithOS configureNetwork(Azure client, WithNetwork initialVMBuilder) { * Configures OS Disk, Admin User, and Data Disks * @return {@link WithCreate} VM Definition object ready for final generic configurations */ - private WithCreate configureOS(Azure client, WithOS withOS) { - switch(getOsType()) { + private WithCreate configureOS(AzureResourceManager client, VirtualMachine.DefinitionStages.WithOS withOS) { + switch (getOsType()) { case "linux": return configureLinux(client, withOS); case "windows": @@ -898,39 +910,44 @@ private WithCreate configureOS(Azure client, WithOS withOS) { * Configures OS Disk, Admin User, and Data Disks * @return {@link WithCreate} VM Definition object ready for final generic configurations */ - private WithCreate configureLinux(Azure client, WithOS withOS) { + private WithCreate configureLinux(AzureResourceManager client, WithOS withOS) { switch (getVmImageType()) { case "custom": return configureLinuxManaged( - client, - withOS.withLinuxCustomImage(getCustomImage())); + client, + withOS.withGeneralizedLinuxCustomImage(getCustomImage())); case "gallery": return configureLinuxManaged( - client, - withOS.withLinuxGalleryImageVersion(getGalleryImageVersion())); + client, + withOS.withGeneralizedLinuxGalleryImageVersion(getGalleryImageVersion())); case "latest": return configureLinuxManagedOrUnmanaged( - client, - withOS.withLatestLinuxImage(getImagePublisher(), getImageOffer(), getImageSku())); + client, + withOS.withLatestLinuxImage(getImagePublisher(), getImageOffer(), getImageSku())); case "popular": return configureLinuxManagedOrUnmanaged( - client, - withOS.withPopularLinuxImage(KnownLinuxVirtualMachineImage.valueOf(getKnownVirtualImage()))); + client, + withOS.withPopularLinuxImage(KnownLinuxVirtualMachineImage.valueOf(getKnownVirtualImage()))); case "specific": return configureLinuxManagedOrUnmanaged( - client, - withOS.withSpecificLinuxImageVersion( - client.virtualMachineImages() - .getImage(getImageRegion(), getImagePublisher(), getImageOffer(), getImageSku(), getImageVersion()) - .imageReference())); + client, + withOS.withSpecificLinuxImageVersion( + client.virtualMachineImages() + .getImage( + getImageRegion(), + getImagePublisher(), + getImageOffer(), + getImageSku(), + getImageVersion()) + .imageReference())); case "stored": return configureLinuxUnmanaged( - client, - withOS.withStoredLinuxImage(getStoredImage())); + client, + withOS.withStoredLinuxImage(getStoredImage())); case "specialized": // Only Managed Disks are supported by Gyro currently WithManagedCreate specializedOsManagedConfigured = withOS.withSpecializedOSDisk( - client.disks().getById(getOsDisk().getId()), OperatingSystemTypes.LINUX); + client.disks().getById(getOsDisk().getId()), OperatingSystemTypes.LINUX); return configureManagedDataDisks(client, specializedOsManagedConfigured); default: throw new GyroException(String.format("Linux VM Image Type [%s] is Unsupported!", getVmImageType())); @@ -941,15 +958,21 @@ private WithCreate configureLinux(Azure client, WithOS withOS) { * Helper method in Virtual Machine workflow. Handles Managed Disk types. * @return {@link WithCreate} VM Definition object ready for final generic configurations */ - private WithCreate configureLinuxManaged(Azure client, WithLinuxRootUsernameManaged vmImageTypeConfigured) { - return configureManagedDataDisks(client, configureLinuxAdmin(vmImageTypeConfigured).withCustomData(getEncodedCustomData())); + private WithCreate configureLinuxManaged( + AzureResourceManager client, + WithLinuxRootUsernameManaged vmImageTypeConfigured) { + return configureManagedDataDisks( + client, + configureLinuxAdmin(vmImageTypeConfigured).withCustomData(getEncodedCustomData())); } /** * Helper method in Virtual Machine workflow. Handles ManagedOrUnmanaged Disk types. * @return {@link WithCreate} VM Definition object ready for final generic configurations */ - private WithCreate configureLinuxManagedOrUnmanaged(Azure client, WithLinuxRootUsernameManagedOrUnmanaged vmImageTypeConfigured) { + private WithCreate configureLinuxManagedOrUnmanaged( + AzureResourceManager client, + WithLinuxRootUsernameManagedOrUnmanaged vmImageTypeConfigured) { WithFromImageCreateOptionsManagedOrUnmanaged adminConfigured = configureLinuxAdmin(vmImageTypeConfigured); // Only managed disks are supported by Gyro currently. return configureManagedDataDisks(client, adminConfigured.withCustomData(getEncodedCustomData())); @@ -959,8 +982,12 @@ private WithCreate configureLinuxManagedOrUnmanaged(Azure client, WithLinuxRootU * Helper method in Virtual Machine workflow. Handles Unmanaged Disk types. * @return {@link WithCreate} VM Definition object ready for final generic configurations */ - private WithCreate configureLinuxUnmanaged(Azure client, WithLinuxRootUsernameUnmanaged vmImageTypeConfigured) { - return configureUnmanagedDataDisks(client, configureLinuxAdmin(vmImageTypeConfigured).withCustomData(getEncodedCustomData())); + private WithCreate configureLinuxUnmanaged( + AzureResourceManager client, + WithLinuxRootUsernameUnmanaged vmImageTypeConfigured) { + return configureUnmanagedDataDisks( + client, + configureLinuxAdmin(vmImageTypeConfigured).withCustomData(getEncodedCustomData())); } /** @@ -969,7 +996,8 @@ private WithCreate configureLinuxUnmanaged(Azure client, WithLinuxRootUsernameUn */ private WithFromImageCreateOptionsManaged configureLinuxAdmin(WithLinuxRootUsernameManaged vmImageTypeConfigured) { WithLinuxCreateManaged adminConfigured = null; - WithLinuxRootPasswordOrPublicKeyManaged rootUserConfigured = vmImageTypeConfigured.withRootUsername(getAdminUserName()); + WithLinuxRootPasswordOrPublicKeyManaged rootUserConfigured = vmImageTypeConfigured.withRootUsername( + getAdminUserName()); if (!StringUtils.isBlank(getAdminPassword())) { adminConfigured = rootUserConfigured.withRootPassword(getAdminPassword()); } @@ -991,7 +1019,8 @@ private WithFromImageCreateOptionsManaged configureLinuxAdmin(WithLinuxRootUsern */ private WithFromImageCreateOptionsManagedOrUnmanaged configureLinuxAdmin(WithLinuxRootUsernameManagedOrUnmanaged vmImageTypeConfigured) { WithLinuxCreateManagedOrUnmanaged adminConfigured = null; - WithLinuxRootPasswordOrPublicKeyManagedOrUnmanaged rootUserConfigured = vmImageTypeConfigured.withRootUsername(getAdminUserName()); + WithLinuxRootPasswordOrPublicKeyManagedOrUnmanaged rootUserConfigured = vmImageTypeConfigured.withRootUsername( + getAdminUserName()); if (!StringUtils.isBlank(getAdminPassword())) { adminConfigured = rootUserConfigured.withRootPassword(getAdminPassword()); } @@ -1013,7 +1042,8 @@ private WithFromImageCreateOptionsManagedOrUnmanaged configureLinuxAdmin(WithLin */ private WithFromImageCreateOptionsUnmanaged configureLinuxAdmin(WithLinuxRootUsernameUnmanaged vmImageTypeConfigured) { WithLinuxCreateUnmanaged adminConfigured = null; - WithLinuxRootPasswordOrPublicKeyUnmanaged rootUserConfigured = vmImageTypeConfigured.withRootUsername(getAdminUserName()); + WithLinuxRootPasswordOrPublicKeyUnmanaged rootUserConfigured = vmImageTypeConfigured.withRootUsername( + getAdminUserName()); if (!StringUtils.isBlank(getAdminPassword())) { adminConfigured = rootUserConfigured.withRootPassword(getAdminPassword()); } @@ -1034,40 +1064,45 @@ private WithFromImageCreateOptionsUnmanaged configureLinuxAdmin(WithLinuxRootUse * Configures OS Disk, Admin User, and Data Disks * @return {@link WithCreate} VM Definition object ready for final generic configurations */ - private WithCreate configureWindows(Azure client, WithOS withOS) { + private WithCreate configureWindows(AzureResourceManager client, WithOS withOS) { switch (getVmImageType()) { case "custom": return configureWindowsManaged( - client, - withOS.withWindowsCustomImage(getCustomImage())); + client, + withOS.withGeneralizedWindowsCustomImage(getCustomImage())); case "gallery": return configureWindowsManaged( - client, - withOS.withWindowsGalleryImageVersion(getGalleryImageVersion())); + client, + withOS.withGeneralizedWindowsGalleryImageVersion(getGalleryImageVersion())); case "latest": return configureWindowsManagedOrUnmanaged( - client, - withOS.withLatestWindowsImage(getImagePublisher(), getImageOffer(), getImageSku())); + client, + withOS.withLatestWindowsImage(getImagePublisher(), getImageOffer(), getImageSku())); case "popular": return configureWindowsManagedOrUnmanaged( - client, - withOS.withPopularWindowsImage(KnownWindowsVirtualMachineImage.valueOf(getKnownVirtualImage()))); + client, + withOS.withPopularWindowsImage(KnownWindowsVirtualMachineImage.valueOf(getKnownVirtualImage()))); case "specific": return configureWindowsManagedOrUnmanaged( - client, - withOS.withSpecificWindowsImageVersion( - client.virtualMachineImages() - .getImage(getImageRegion(), getImagePublisher(), getImageOffer(), getImageSku(), getImageVersion()) - .imageReference())); + client, + withOS.withSpecificWindowsImageVersion( + client.virtualMachineImages() + .getImage( + getImageRegion(), + getImagePublisher(), + getImageOffer(), + getImageSku(), + getImageVersion()) + .imageReference())); case "stored": return configureWindowsUnmanaged( - client, - withOS.withStoredWindowsImage(getStoredImage())); + client, + withOS.withStoredWindowsImage(getStoredImage())); case "specialized": // Only Managed Disks are supported by Gyro currently WithManagedCreate specializedOsManagedConfigured = withOS.withSpecializedOSDisk( - client.disks().getById(getOsDisk().getId()), OperatingSystemTypes.WINDOWS); + client.disks().getById(getOsDisk().getId()), OperatingSystemTypes.WINDOWS); return configureManagedDataDisks(client, specializedOsManagedConfigured); default: throw new GyroException(String.format("Windows VM Image Type [%s] is Unsupported!", getVmImageType())); @@ -1078,40 +1113,46 @@ private WithCreate configureWindows(Azure client, WithOS withOS) { * Helper method in Virtual Machine Fluent workflow. Handles Managed Disk types. * @return {@link WithCreate} VM Definition object ready for final generic configurations */ - private WithCreate configureWindowsManaged(Azure client, WithWindowsAdminUsernameManaged vmImageTypeConfigured) { + private WithCreate configureWindowsManaged( + AzureResourceManager client, + WithWindowsAdminUsernameManaged vmImageTypeConfigured) { WithWindowsCreateManaged adminConfigured = configureWindowsAdmin(vmImageTypeConfigured); return configureManagedDataDisks( - client, - adminConfigured.withoutAutoUpdate() - .withoutVMAgent() - .withTimeZone(getTimeZone()) - .withCustomData(getEncodedCustomData())); + client, + adminConfigured.withoutAutoUpdate() + .withoutVMAgent() + .withTimeZone(getTimeZone()) + .withCustomData(getEncodedCustomData())); } /** * Helper method in Virtual Machine Fluent workflow. Handles ManagedOrUnmanaged Disk types. * @return {@link WithCreate} VM Definition object ready for final generic configurations */ - private WithCreate configureWindowsManagedOrUnmanaged(Azure client, WithWindowsAdminUsernameManagedOrUnmanaged vmImageTypeConfigured) { + private WithCreate configureWindowsManagedOrUnmanaged( + AzureResourceManager client, + WithWindowsAdminUsernameManagedOrUnmanaged vmImageTypeConfigured) { WithWindowsCreateManagedOrUnmanaged adminConfigured = configureWindowsAdmin(vmImageTypeConfigured); // Only managed disks are supported by Gyro currently. return configureManagedDataDisks( - client, - adminConfigured.withoutAutoUpdate() - .withoutVMAgent() - .withTimeZone(getTimeZone()) - .withCustomData(getEncodedCustomData())); + client, + adminConfigured.withoutAutoUpdate() + .withoutVMAgent() + .withTimeZone(getTimeZone()) + .withCustomData(getEncodedCustomData())); } /** * Helper method in Virtual Machine Fluent workflow. Handles Unmanaged Disk types. * @return {@link WithCreate} VM Definition object ready for final generic configurations */ - private WithCreate configureWindowsUnmanaged(Azure client, WithWindowsAdminUsernameUnmanaged vmImageTypeConfigured) { + private WithCreate configureWindowsUnmanaged( + AzureResourceManager client, + WithWindowsAdminUsernameUnmanaged vmImageTypeConfigured) { return configureUnmanagedDataDisks( - client, - configureWindowsAdmin(vmImageTypeConfigured).withCustomData(getEncodedCustomData())); + client, + configureWindowsAdmin(vmImageTypeConfigured).withCustomData(getEncodedCustomData())); } /** @@ -1120,7 +1161,7 @@ private WithCreate configureWindowsUnmanaged(Azure client, WithWindowsAdminUsern */ private WithWindowsCreateManaged configureWindowsAdmin(WithWindowsAdminUsernameManaged vmImageTypeConfigured) { return vmImageTypeConfigured.withAdminUsername(getAdminUserName()) - .withAdminPassword(getAdminPassword()); + .withAdminPassword(getAdminPassword()); } /** @@ -1129,7 +1170,7 @@ private WithWindowsCreateManaged configureWindowsAdmin(WithWindowsAdminUsernameM */ private WithWindowsCreateManagedOrUnmanaged configureWindowsAdmin(WithWindowsAdminUsernameManagedOrUnmanaged vmImageTypeConfigured) { return vmImageTypeConfigured.withAdminUsername(getAdminUserName()) - .withAdminPassword(getAdminPassword()); + .withAdminPassword(getAdminPassword()); } /** @@ -1138,7 +1179,7 @@ private WithWindowsCreateManagedOrUnmanaged configureWindowsAdmin(WithWindowsAdm */ private WithWindowsCreateUnmanaged configureWindowsAdmin(WithWindowsAdminUsernameUnmanaged vmImageTypeConfigured) { return vmImageTypeConfigured.withAdminUsername(getAdminUserName()) - .withAdminPassword(getAdminPassword()); + .withAdminPassword(getAdminPassword()); } /** @@ -1146,11 +1187,11 @@ private WithWindowsCreateUnmanaged configureWindowsAdmin(WithWindowsAdminUsernam * Configures Managed Data Disks and Managed Data Disk defaults. * @return {@link WithCreate} VM Definition object ready for final generic configurations */ - private WithCreate configureManagedDataDisks(Azure client, WithManagedCreate adminConfigured) { + private WithCreate configureManagedDataDisks(AzureResourceManager client, WithManagedCreate adminConfigured) { WithManagedCreate diskDefaultsConfigured = adminConfigured - .withDataDiskDefaultCachingType(CachingTypes.fromString(getCachingType())) - .withDataDiskDefaultStorageAccountType(StorageAccountTypes.fromString(getStorageAccountTypeDataDisk())) - .withOSDiskStorageAccountType(StorageAccountTypes.fromString(getStorageAccountTypeOsDisk())); + .withDataDiskDefaultCachingType(CachingTypes.fromString(getCachingType())) + .withDataDiskDefaultStorageAccountType(StorageAccountTypes.fromString(getStorageAccountTypeDataDisk())) + .withOSDiskStorageAccountType(StorageAccountTypes.fromString(getStorageAccountTypeOsDisk())); for (DiskResource diskResource : getDataDisks()) { Disk disk = client.disks().getById(diskResource.getId()); @@ -1166,7 +1207,9 @@ private WithCreate configureManagedDataDisks(Azure client, WithManagedCreate adm * Fifth step in Virtual Machine Fluent workflow. Configures Data disks * @return {@link WithCreate} VM Definition object ready for final generic configurations */ - private WithCreate configureDataDisks(Azure client, T adminConfigured) { + private WithCreate configureDataDisks( + AzureResourceManager client, + T adminConfigured) { // Only managed disks are supported by Gyro currently. return configureManagedDataDisks(client, adminConfigured); } @@ -1175,7 +1218,9 @@ private WithCreate conf * Fifth step in Virtual Machine Fluent workflow. Configures Data disks * @return {@link WithCreate} VM Definition object ready for final generic configurations */ - private WithCreate configureUnmanagedDataDisks(Azure client, WithUnmanagedCreate adminConfigured) { + private WithCreate configureUnmanagedDataDisks( + AzureResourceManager client, + VirtualMachine.DefinitionStages.WithUnmanagedCreate adminConfigured) { // Only managed disks are supported by Gyro currently. if (!getDataDisks().isEmpty()) { throw new GyroException("Unmanaged Data Disks are currently not supported by Gyro"); @@ -1186,7 +1231,7 @@ private WithCreate configureUnmanagedDataDisks(Azure client, WithUnmanagedCreate @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); VirtualMachine virtualMachine = client.virtualMachines().getById(getId()); @@ -1203,10 +1248,10 @@ public void update(GyroUI ui, State state, Resource current, Set changed } Set wantedDataDiskIds = getDataDisks() - .stream() - .map(DiskResource::getId) - .filter(s -> client.disks().getById(s) != null) - .collect(Collectors.toSet()); + .stream() + .map(DiskResource::getId) + .filter(s -> client.disks().getById(s) != null) + .collect(Collectors.toSet()); Set diskIdsToRemove = new LinkedHashSet<>(currentDataDiskIdsToLun.keySet()); diskIdsToRemove.removeAll(wantedDataDiskIds); @@ -1240,7 +1285,8 @@ public void update(GyroUI ui, State state, Resource current, Set changed } for (IdentityResource identity : getIdentities()) { - update = update.withExistingUserAssignedManagedServiceIdentity(client.identities().getById(identity.getId())); + update = update.withExistingUserAssignedManagedServiceIdentity(client.identities() + .getById(identity.getId())); } } @@ -1250,20 +1296,22 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); VirtualMachine virtualMachine = client.virtualMachines().getById(getId()); client.virtualMachines().deleteById(getId()); if (getDeleteOsDiskOnTerminate() - && virtualMachine != null - && !"specialized".equals(getVmImageType())) { + && virtualMachine != null + && !"specialized".equals(getVmImageType())) { client.disks().deleteById(virtualMachine.osDiskId()); } } private String getEncodedCustomData() { - return !ObjectUtils.isBlank(getCustomData()) ? Base64.getEncoder().encodeToString(getCustomData().getBytes()) : null; + return !ObjectUtils.isBlank(getCustomData()) + ? Base64.getEncoder().encodeToString(getCustomData().getBytes()) + : null; } private String getDecodedCustomData(String data) { @@ -1276,46 +1324,82 @@ public List validate() { if ("custom".equals(getVmImageType())) { if (getCustomImage() == null) { - errors.add(new ValidationError(this, "custom-image", "[custom-image] is required when using 'custom' [os-type]!")); + errors.add(new ValidationError( + this, + "custom-image", + "[custom-image] is required when using 'custom' [os-type]!")); } } else if ("gallery".equals(getVmImageType())) { if (getGalleryImageVersion() == null) { - errors.add(new ValidationError(this, "gallery-image-version", "[gallery-image-version] is required when using 'gallery' [os-type]!")); + errors.add(new ValidationError( + this, + "gallery-image-version", + "[gallery-image-version] is required when using 'gallery' [os-type]!")); } } else if ("latest".equals(getVmImageType())) { if (getImagePublisher() == null) { - errors.add(new ValidationError(this, "image-publisher", "[image-publisher] is required when using 'latest' [os-type]!")); + errors.add(new ValidationError( + this, + "image-publisher", + "[image-publisher] is required when using 'latest' [os-type]!")); } if (getImageOffer() == null) { - errors.add(new ValidationError(this, "image-offer", "[image-offer] is required when using 'latest' [os-type]!")); + errors.add(new ValidationError( + this, + "image-offer", + "[image-offer] is required when using 'latest' [os-type]!")); } if (getImageSku() == null) { - errors.add(new ValidationError(this, "image-sku", "[image-sku] is required when using 'latest' [os-type]!")); + errors.add(new ValidationError( + this, + "image-sku", + "[image-sku] is required when using 'latest' [os-type]!")); } } else if ("popular".equals(getVmImageType())) { if (getKnownVirtualImage() == null) { - errors.add(new ValidationError(this, "known-virtual-image", "[known-virtual-image] is required when using 'popular' [os-type]!")); + errors.add(new ValidationError( + this, + "known-virtual-image", + "[known-virtual-image] is required when using 'popular' [os-type]!")); } } else if ("specific".equals(getVmImageType())) { if (getImageRegion() == null) { - errors.add(new ValidationError(this, "image-region", "[image-region] is required when using 'specific' [os-type]!")); + errors.add(new ValidationError( + this, + "image-region", + "[image-region] is required when using 'specific' [os-type]!")); } if (getImagePublisher() == null) { - errors.add(new ValidationError(this, "image-publisher", "[image-publisher] is required when using 'specific' [os-type]!")); + errors.add(new ValidationError( + this, + "image-publisher", + "[image-publisher] is required when using 'specific' [os-type]!")); } if (getImageSku() == null) { - errors.add(new ValidationError(this, "image-sku", "[image-sku] is required when using 'specific' [os-type]!")); + errors.add(new ValidationError( + this, + "image-sku", + "[image-sku] is required when using 'specific' [os-type]!")); } if (getImageVersion() == null) { - errors.add(new ValidationError(this, "image-version", "[image-version] is required when using 'specific' [os-type]!")); + errors.add(new ValidationError( + this, + "image-version", + "[image-version] is required when using 'specific' [os-type]!")); } } else if ("stored".equals(getVmImageType())) { if (getStoredImage() == null) { - errors.add(new ValidationError(this, "stored-image", "[stored-image] is required when using 'stored' [os-type]!")); + errors.add(new ValidationError( + this, + "stored-image", + "[stored-image] is required when using 'stored' [os-type]!")); } } else if ("specialized".equals(getVmImageType())) { if (getOsDisk() == null) { - errors.add(new ValidationError(this, "os-disk", "[os-disk] is required when using 'specialized' [os-type]!")); + errors.add(new ValidationError( + this, + "os-disk", + "[os-disk] is required when using 'specialized' [os-type]!")); } } else { errors.add(new ValidationError(this, "vm-image-type", "Unsupported [vm-image-type]!")); @@ -1343,12 +1427,16 @@ public String getGyroInstancePrivateIpAddress() { @Override public String getGyroInstancePublicIpAddress() { - return getPublicIpAddress() != null && !ObjectUtils.isBlank(getPublicIpAddress().getIpAddress()) ? getPublicIpAddress().getIpAddress() : getPublicIpAddressIp(); + return getPublicIpAddress() != null && !ObjectUtils.isBlank(getPublicIpAddress().getIpAddress()) + ? getPublicIpAddress().getIpAddress() + : getPublicIpAddressIp(); } @Override public String getGyroInstanceHostname() { - return getGyroInstancePublicIpAddress() != null ? getGyroInstancePublicIpAddress() : getGyroInstancePrivateIpAddress(); + return getGyroInstancePublicIpAddress() != null + ? getGyroInstancePublicIpAddress() + : getGyroInstancePrivateIpAddress(); } @Override From 46304ec6c41e87bc52d032e9b64bf0e5421081bc Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Wed, 25 May 2022 15:10:39 -0400 Subject: [PATCH 31/43] initial cdn refactor --- .../gyro/azure/cdn/CdnEndpointResource.java | 88 +++++++++++-------- .../java/gyro/azure/cdn/CdnProfileFinder.java | 20 +++-- .../gyro/azure/cdn/CdnProfileResource.java | 40 ++++----- src/main/java/gyro/azure/cdn/GeoFilter.java | 20 ++--- 4 files changed, 90 insertions(+), 78 deletions(-) diff --git a/src/main/java/gyro/azure/cdn/CdnEndpointResource.java b/src/main/java/gyro/azure/cdn/CdnEndpointResource.java index 042b6cb1..296d4bdb 100644 --- a/src/main/java/gyro/azure/cdn/CdnEndpointResource.java +++ b/src/main/java/gyro/azure/cdn/CdnEndpointResource.java @@ -16,31 +16,28 @@ package gyro.azure.cdn; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.cdn.models.CdnEndpoint; +import com.azure.resourcemanager.cdn.models.CdnProfile; +import com.azure.resourcemanager.cdn.models.QueryStringCachingBehavior; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.core.GyroUI; import gyro.core.resource.Resource; import gyro.core.resource.Updatable; - -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.cdn.CdnProfile; -import com.microsoft.azure.management.cdn.CdnEndpoint; -import com.microsoft.azure.management.cdn.QueryStringCachingBehavior; -import com.microsoft.azure.management.cdn.CdnEndpoint.UpdateDefinitionStages.WithPremiumAttach; -import com.microsoft.azure.management.cdn.CdnEndpoint.UpdateDefinitionStages.WithStandardAttach; import gyro.core.scope.State; import gyro.core.validation.Required; import gyro.core.validation.ValidStrings; import gyro.core.validation.ValidationError; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - /** * Creates a cdn endpoint. * @@ -267,7 +264,7 @@ public void setOriginHostname(String originHostname) { /** * Determines the query caching behavior. */ - @ValidStrings({"IGNORE_QUERY_STRING", "BYPASS_CACHING", "USE_QUERY_STRING"}) + @ValidStrings({ "IGNORE_QUERY_STRING", "BYPASS_CACHING", "USE_QUERY_STRING" }) @Updatable public String getQueryCachingBehavior() { return queryCachingBehavior; @@ -296,7 +293,7 @@ public void setTags(Map tags) { /** * The type of the endpoint. Defaults to ``Standard``. */ - @ValidStrings({"Standard", "Premium"}) + @ValidStrings({ "Standard", "Premium" }) public String getType() { if (type == null) { type = TYPE_STANDARD; @@ -342,15 +339,15 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); CdnProfileResource parent = (CdnProfileResource) parent(); CdnProfile cdnProfile = client.cdnProfiles().getById(parent.getId()); if (TYPE_PREMIUM.equalsIgnoreCase(getType())) { - WithPremiumAttach createPremiumEndpoint = - cdnProfile.update().defineNewPremiumEndpoint(getName(), getOriginHostname()); + CdnEndpoint.UpdateDefinitionStages.WithPremiumAttach createPremiumEndpoint = + cdnProfile.update().defineNewPremiumEndpoint(getName(), getOriginHostname()); if (getHostHeader() != null) { createPremiumEndpoint.withHostHeader(getHostHeader()); @@ -383,12 +380,12 @@ public void create(GyroUI ui, State state) { copyFrom(profile.endpoints().get(getName())); } else if (TYPE_STANDARD.equalsIgnoreCase(getType())) { - WithStandardAttach createStandardEndpoint = - cdnProfile.update().defineNewEndpoint(getName(), getOriginHostname()); + CdnEndpoint.UpdateDefinitionStages.WithStandardAttach createStandardEndpoint = + cdnProfile.update().defineNewEndpoint(getName(), getOriginHostname()); if (getCompressionEnabled() != null && getContentTypesToCompress() != null) { createStandardEndpoint.withCompressionEnabled(getCompressionEnabled()) - .withContentTypesToCompress(getContentTypesToCompress()); + .withContentTypesToCompress(getContentTypesToCompress()); } if (!getGeoFilter().isEmpty()) { @@ -419,8 +416,8 @@ public void create(GyroUI ui, State state) { if (getQueryCachingBehavior() != null) { createStandardEndpoint - .withQueryStringCachingBehavior(QueryStringCachingBehavior - .valueOf(getQueryCachingBehavior())); + .withQueryStringCachingBehavior(QueryStringCachingBehavior + .valueOf(getQueryCachingBehavior())); } for (String customDomain : getCustomDomains()) { @@ -435,7 +432,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); CdnProfileResource parent = (CdnProfileResource) parent(); @@ -443,7 +440,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed if (TYPE_PREMIUM.equalsIgnoreCase(getType())) { CdnEndpoint.UpdatePremiumEndpoint updatePremiumEndpoint = - cdnProfile.update().updatePremiumEndpoint(getName()); + cdnProfile.update().updatePremiumEndpoint(getName()); if (getHostHeader() != null) { updatePremiumEndpoint.withHostHeader(getHostHeader()); @@ -476,12 +473,12 @@ public void update(GyroUI ui, State state, Resource current, Set changed } else if (TYPE_STANDARD.equalsIgnoreCase(getType())) { CdnEndpoint.UpdateStandardEndpoint updateStandardEndpoint = - cdnProfile + cdnProfile .update().updateEndpoint(getName()); if (getCompressionEnabled() != null && getContentTypesToCompress() != null) { updateStandardEndpoint.withCompressionEnabled(getCompressionEnabled()) - .withContentTypesToCompress(getContentTypesToCompress()); + .withContentTypesToCompress(getContentTypesToCompress()); } if (!getGeoFilter().isEmpty()) { @@ -512,7 +509,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed if (getQueryCachingBehavior() != null) { updateStandardEndpoint - .withQueryStringCachingBehavior(QueryStringCachingBehavior + .withQueryStringCachingBehavior(QueryStringCachingBehavior .valueOf(getQueryCachingBehavior())); } @@ -527,7 +524,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); CdnProfileResource parent = (CdnProfileResource) parent(); @@ -538,8 +535,8 @@ public void delete(GyroUI ui, State state) { update.apply(); } - private List toGeoFilters() { - List geoFilters = new ArrayList<>(); + private List toGeoFilters() { + List geoFilters = new ArrayList<>(); getGeoFilter().forEach(geo -> geoFilters.add(geo.toGeoFilter())); @@ -565,23 +562,38 @@ public List validate() { List errors = new ArrayList<>(); if (!getHttpEnabled() && !getHttpsEnabled()) { - errors.add(new ValidationError(this, null, "Both 'http-enabled' and 'https-enabled' cannot be set to false.")); + errors.add(new ValidationError( + this, + null, + "Both 'http-enabled' and 'https-enabled' cannot be set to false.")); } if (!getHttpEnabled() && getHttpPort() != null) { - errors.add(new ValidationError(this, "http-port", "'http-port' cannot be configured when 'http-enabled' is set to false.")); + errors.add(new ValidationError( + this, + "http-port", + "'http-port' cannot be configured when 'http-enabled' is set to false.")); } if (getHttpEnabled() && getHttpPort() == null) { - errors.add(new ValidationError(this, "http-port", "'http-port' is required when 'http-enabled' is set to true.")); + errors.add(new ValidationError( + this, + "http-port", + "'http-port' is required when 'http-enabled' is set to true.")); } if (!getHttpsEnabled() && getHttpsPort() != null) { - errors.add(new ValidationError(this, "https-port", "'https-port' cannot be configured when 'https-enabled' is set to false.")); + errors.add(new ValidationError( + this, + "https-port", + "'https-port' cannot be configured when 'https-enabled' is set to false.")); } if (getHttpsEnabled() && getHttpsPort() == null) { - errors.add(new ValidationError(this, "https-port", "'https-port' is required when 'https-enabled' is set to true.")); + errors.add(new ValidationError( + this, + "https-port", + "'https-port' is required when 'https-enabled' is set to true.")); } return errors; diff --git a/src/main/java/gyro/azure/cdn/CdnProfileFinder.java b/src/main/java/gyro/azure/cdn/CdnProfileFinder.java index a3254d6a..1c6fb2f4 100644 --- a/src/main/java/gyro/azure/cdn/CdnProfileFinder.java +++ b/src/main/java/gyro/azure/cdn/CdnProfileFinder.java @@ -16,14 +16,15 @@ package gyro.azure.cdn; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.cdn.CdnProfile; -import gyro.azure.AzureFinder; -import gyro.core.Type; - import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; + +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.cdn.models.CdnProfile; +import gyro.azure.AzureResourceManagerFinder; +import gyro.core.Type; /** * Query cdn profile. @@ -36,7 +37,8 @@ * cdn-profile: $(external-query azure::cdn-profile {}) */ @Type("cdn-profile") -public class CdnProfileFinder extends AzureFinder { +public class CdnProfileFinder extends AzureResourceManagerFinder { + private String id; /** @@ -51,12 +53,12 @@ public void setId(String id) { } @Override - protected List findAllAzure(Azure client) { - return client.cdnProfiles().list(); + protected List findAllAzure(AzureResourceManager client) { + return client.cdnProfiles().list().stream().collect(Collectors.toList()); } @Override - protected List findAzure(Azure client, Map filters) { + protected List findAzure(AzureResourceManager client, Map filters) { CdnProfile cdnProfile = client.cdnProfiles().getById(filters.get("id")); if (cdnProfile == null) { return Collections.emptyList(); diff --git a/src/main/java/gyro/azure/cdn/CdnProfileResource.java b/src/main/java/gyro/azure/cdn/CdnProfileResource.java index 8a8d739d..95868498 100644 --- a/src/main/java/gyro/azure/cdn/CdnProfileResource.java +++ b/src/main/java/gyro/azure/cdn/CdnProfileResource.java @@ -16,30 +16,28 @@ package gyro.azure.cdn; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import com.azure.core.management.Region; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.cdn.models.CdnProfile; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.azure.resources.ResourceGroupResource; import gyro.core.GyroUI; +import gyro.core.Type; import gyro.core.resource.Id; -import gyro.core.resource.Resource; import gyro.core.resource.Output; -import gyro.core.Type; +import gyro.core.resource.Resource; import gyro.core.resource.Updatable; - -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.cdn.CdnProfile; -import com.microsoft.azure.management.cdn.CdnProfile.DefinitionStages.WithSku; -import com.microsoft.azure.management.resources.fluentcore.arm.Region; import gyro.core.scope.State; import gyro.core.validation.Required; import gyro.core.validation.ValidStrings; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - /** * Creates a cdn profile. * @@ -108,7 +106,7 @@ public void setResourceGroup(ResourceGroupResource resourceGroup) { * The sku of the CDN Profile. */ @Required - @ValidStrings({"Premium_Verizon", "Standard_Verizon", "Standard_Akamai"}) + @ValidStrings({ "Premium_Verizon", "Standard_Verizon", "Standard_Akamai" }) public String getSku() { return sku; } @@ -167,7 +165,7 @@ public void copyFrom(CdnProfile cdnProfile) { @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); CdnProfile cdnProfile = client.cdnProfiles().getById(getId()); @@ -182,11 +180,11 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); - WithSku withSku = client.cdnProfiles().define(getName()) - .withRegion(Region.fromName(getRegion())) - .withExistingResourceGroup(getResourceGroup().getName()); + CdnProfile.DefinitionStages.WithSku withSku = client.cdnProfiles().define(getName()) + .withRegion(Region.fromName(getRegion())) + .withExistingResourceGroup(getResourceGroup().getName()); CdnProfile cdnProfile = null; if ("Premium_Verizon".equalsIgnoreCase(getSku())) { @@ -202,7 +200,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); CdnProfile.Update update = client.cdnProfiles().getById(getId()).update().withTags(getTags()); update.apply(); @@ -210,7 +208,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); client.cdnProfiles().deleteById(getId()); } diff --git a/src/main/java/gyro/azure/cdn/GeoFilter.java b/src/main/java/gyro/azure/cdn/GeoFilter.java index 84948723..e05d3273 100644 --- a/src/main/java/gyro/azure/cdn/GeoFilter.java +++ b/src/main/java/gyro/azure/cdn/GeoFilter.java @@ -16,17 +16,17 @@ package gyro.azure.cdn; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Set; + +import com.azure.resourcemanager.cdn.models.GeoFilterActions; import gyro.azure.Copyable; import gyro.core.resource.Diffable; -import com.microsoft.azure.management.cdn.GeoFilterActions; import gyro.core.validation.Required; import gyro.core.validation.ValidStrings; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Set; - -public class GeoFilter extends Diffable implements Copyable { +public class GeoFilter extends Diffable implements Copyable { private String action; private Set countryCodes; @@ -36,7 +36,7 @@ public class GeoFilter extends Diffable implements Copyable(geoFilter.countryCodes())); setRelativePath(geoFilter.relativePath()); @@ -84,8 +84,8 @@ public String primaryKey() { return String.format("%s/%s/%s", getAction(), getCountryCodes(), getRelativePath()); } - public com.microsoft.azure.management.cdn.GeoFilter toGeoFilter() { - com.microsoft.azure.management.cdn.GeoFilter geoFilter = new com.microsoft.azure.management.cdn.GeoFilter(); + public com.azure.resourcemanager.cdn.models.GeoFilter toGeoFilter() { + com.azure.resourcemanager.cdn.models.GeoFilter geoFilter = new com.azure.resourcemanager.cdn.models.GeoFilter(); geoFilter.withAction(GeoFilterActions.fromString(getAction())); geoFilter.withCountryCodes(new ArrayList<>(getCountryCodes())); From f191e6eb8a4fc30257f546ee64f5b2b4e8a01c02 Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Wed, 25 May 2022 15:17:04 -0400 Subject: [PATCH 32/43] initial accessmanagement refactor --- .../ActiveDirectoryGroupFinder.java | 23 +++++++++++-------- .../ActiveDirectoryGroupResource.java | 15 ++++++------ .../ActiveDirectoryUserFinder.java | 23 +++++++++++-------- .../ActiveDirectoryUserResource.java | 19 +++++++-------- .../accessmanagement/ApplicationResource.java | 6 ++++- .../RoleAssignmentResource.java | 11 +++++---- 6 files changed, 55 insertions(+), 42 deletions(-) diff --git a/src/main/java/gyro/azure/accessmanagement/ActiveDirectoryGroupFinder.java b/src/main/java/gyro/azure/accessmanagement/ActiveDirectoryGroupFinder.java index 2a1a3c1b..9b0bb990 100644 --- a/src/main/java/gyro/azure/accessmanagement/ActiveDirectoryGroupFinder.java +++ b/src/main/java/gyro/azure/accessmanagement/ActiveDirectoryGroupFinder.java @@ -16,15 +16,16 @@ package gyro.azure.accessmanagement; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.graphrbac.ActiveDirectoryGroup; -import gyro.azure.AzureFinder; -import gyro.core.GyroException; -import gyro.core.Type; - import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; + +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.authorization.models.ActiveDirectoryGroup; +import gyro.azure.AzureResourceManagerFinder; +import gyro.core.GyroException; +import gyro.core.Type; /** * Query active directory group. @@ -37,7 +38,9 @@ * active-directory-group: $(external-query azure::active-directory-group {name: "gyro"}) */ @Type("active-directory-group") -public class ActiveDirectoryGroupFinder extends AzureFinder { +public class ActiveDirectoryGroupFinder + extends AzureResourceManagerFinder { + private String name; private String id; @@ -64,12 +67,12 @@ public void setId(String id) { } @Override - protected List findAllAzure(Azure client) { - return client.accessManagement().activeDirectoryGroups().list(); + protected List findAllAzure(AzureResourceManager client) { + return client.accessManagement().activeDirectoryGroups().list().stream().collect(Collectors.toList()); } @Override - protected List findAzure(Azure client, Map filters) { + protected List findAzure(AzureResourceManager client, Map filters) { ActiveDirectoryGroup group = null; if (filters.containsKey("id")) { group = client.accessManagement().activeDirectoryGroups().getById(filters.get("id")); diff --git a/src/main/java/gyro/azure/accessmanagement/ActiveDirectoryGroupResource.java b/src/main/java/gyro/azure/accessmanagement/ActiveDirectoryGroupResource.java index 7c678fa3..d1aa5b2f 100644 --- a/src/main/java/gyro/azure/accessmanagement/ActiveDirectoryGroupResource.java +++ b/src/main/java/gyro/azure/accessmanagement/ActiveDirectoryGroupResource.java @@ -16,8 +16,10 @@ package gyro.azure.accessmanagement; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.graphrbac.ActiveDirectoryGroup; +import java.util.Set; + +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.authorization.models.ActiveDirectoryGroup; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.core.GyroUI; @@ -28,8 +30,6 @@ import gyro.core.scope.State; import gyro.core.validation.Required; -import java.util.Set; - /** * Creates a active directory group. * @@ -45,6 +45,7 @@ */ @Type("active-directory-group") public class ActiveDirectoryGroupResource extends AzureResource implements Copyable { + private String name; private String emailNick; private String id; @@ -94,7 +95,7 @@ public void copyFrom(ActiveDirectoryGroup group) { @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); ActiveDirectoryGroup group = client.accessManagement().activeDirectoryGroups().getById(getId()); @@ -109,7 +110,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) throws Exception { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); ActiveDirectoryGroup group = client.accessManagement().activeDirectoryGroups() .define(getName()) @@ -126,7 +127,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) throws Exception { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); client.accessManagement().activeDirectoryGroups().deleteById(getId()); } diff --git a/src/main/java/gyro/azure/accessmanagement/ActiveDirectoryUserFinder.java b/src/main/java/gyro/azure/accessmanagement/ActiveDirectoryUserFinder.java index 7631f0e6..4e027065 100644 --- a/src/main/java/gyro/azure/accessmanagement/ActiveDirectoryUserFinder.java +++ b/src/main/java/gyro/azure/accessmanagement/ActiveDirectoryUserFinder.java @@ -16,15 +16,16 @@ package gyro.azure.accessmanagement; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.graphrbac.ActiveDirectoryUser; -import gyro.azure.AzureFinder; -import gyro.core.GyroException; -import gyro.core.Type; - import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; + +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.authorization.models.ActiveDirectoryUser; +import gyro.azure.AzureResourceManagerFinder; +import gyro.core.GyroException; +import gyro.core.Type; /** * Query active directory user. @@ -37,7 +38,9 @@ * active-directory-user: $(external-query azure::active-directory-user {name: "gyro"}) */ @Type("active-directory-user") -public class ActiveDirectoryUserFinder extends AzureFinder { +public class ActiveDirectoryUserFinder + extends AzureResourceManagerFinder { + private String id; private String name; @@ -64,12 +67,12 @@ public void setName(String name) { } @Override - protected List findAllAzure(Azure client) { - return client.accessManagement().activeDirectoryUsers().list(); + protected List findAllAzure(AzureResourceManager client) { + return client.accessManagement().activeDirectoryUsers().list().stream().collect(Collectors.toList()); } @Override - protected List findAzure(Azure client, Map filters) { + protected List findAzure(AzureResourceManager client, Map filters) { ActiveDirectoryUser user = null; if (filters.containsKey("id")) { diff --git a/src/main/java/gyro/azure/accessmanagement/ActiveDirectoryUserResource.java b/src/main/java/gyro/azure/accessmanagement/ActiveDirectoryUserResource.java index 0c4d538c..6aecd4d5 100644 --- a/src/main/java/gyro/azure/accessmanagement/ActiveDirectoryUserResource.java +++ b/src/main/java/gyro/azure/accessmanagement/ActiveDirectoryUserResource.java @@ -16,8 +16,10 @@ package gyro.azure.accessmanagement; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.graphrbac.ActiveDirectoryUser; +import java.util.Set; + +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.authorization.models.ActiveDirectoryUser; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.core.GyroUI; @@ -28,8 +30,6 @@ import gyro.core.scope.State; import gyro.core.validation.Required; -import java.util.Set; - /** * Creates a active directory user. * @@ -46,6 +46,7 @@ */ @Type("active-directory-user") public class ActiveDirectoryUserResource extends AzureResource implements Copyable { + private String name; private String email; private String password; @@ -132,15 +133,15 @@ public void setId(String id) { @Override public void copyFrom(ActiveDirectoryUser user) { setName(user.name()); - setEmail(user.inner().mailNickname()); + setEmail(user.innerModel().mailNickname()); setPrincipalName(user.userPrincipalName()); setId(user.id()); - setAccountEnabled(user.inner().accountEnabled()); + setAccountEnabled(user.innerModel().accountEnabled()); } @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); ActiveDirectoryUser user = client.accessManagement().activeDirectoryUsers().getById(getId()); @@ -155,7 +156,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) throws Exception { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); ActiveDirectoryUser activeDirectoryUser = client.accessManagement().activeDirectoryUsers() .define(getName()) @@ -174,7 +175,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) throws Exception { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); client.accessManagement().activeDirectoryUsers().deleteById(getId()); } diff --git a/src/main/java/gyro/azure/accessmanagement/ApplicationResource.java b/src/main/java/gyro/azure/accessmanagement/ApplicationResource.java index 7f695e76..8336de38 100644 --- a/src/main/java/gyro/azure/accessmanagement/ApplicationResource.java +++ b/src/main/java/gyro/azure/accessmanagement/ApplicationResource.java @@ -75,7 +75,11 @@ public void setName(String name) { @Required @Updatable - @ValidStrings({"AzureADMyOrg", "AzureADMultipleOrgs", "AzureADandPersonalMicrosoftAccount", "PersonalMicrosoftAccount"}) + @ValidStrings({ + "AzureADMyOrg", + "AzureADMultipleOrgs", + "AzureADandPersonalMicrosoftAccount", + "PersonalMicrosoftAccount" }) public String getAccountType() { return accountType; } diff --git a/src/main/java/gyro/azure/accessmanagement/RoleAssignmentResource.java b/src/main/java/gyro/azure/accessmanagement/RoleAssignmentResource.java index e3fb7c3d..ea0bd4c3 100644 --- a/src/main/java/gyro/azure/accessmanagement/RoleAssignmentResource.java +++ b/src/main/java/gyro/azure/accessmanagement/RoleAssignmentResource.java @@ -16,6 +16,11 @@ package gyro.azure.accessmanagement; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Stream; + import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.authorization.models.ActiveDirectoryGroup; import com.azure.resourcemanager.authorization.models.ActiveDirectoryUser; @@ -31,11 +36,6 @@ import gyro.core.scope.State; import gyro.core.validation.Required; -import java.util.Objects; -import java.util.Set; -import java.util.UUID; -import java.util.stream.Stream; - /** * Creates a role assignment. * @@ -52,6 +52,7 @@ */ @Type("role-assignment") public class RoleAssignmentResource extends AzureResource implements Copyable { + private String name; private String scope; private String role; From c033db8d17919c8d8fffba078cd03821cf9e6735 Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Fri, 27 May 2022 16:16:27 -0400 Subject: [PATCH 33/43] initial refactor storage --- build.gradle | 4 + examples/storage/cloud-blob-container.gyro | 10 +- examples/storage/cloud-blob.gyro | 5 +- examples/storage/cloud-file-directory.gyro | 36 ---- examples/storage/cloud-file.gyro | 43 ---- examples/storage/test-cloud-file.txt | 1 - .../storage/CloudBlobContainerResource.java | 92 ++++---- .../gyro/azure/storage/CloudBlobResource.java | 124 ++++------- .../storage/CloudFileDirectoryResource.java | 179 ---------------- .../gyro/azure/storage/CloudFileResource.java | 196 ------------------ .../azure/storage/CloudFileShareResource.java | 96 +++++---- .../azure/storage/CloudQueueResource.java | 87 ++++---- .../azure/storage/CloudTableResource.java | 83 ++++---- src/main/java/gyro/azure/storage/Cors.java | 48 ++--- .../java/gyro/azure/storage/PolicyAction.java | 3 +- .../gyro/azure/storage/PolicyBaseBlob.java | 35 ++-- .../gyro/azure/storage/PolicyDefinition.java | 3 +- .../java/gyro/azure/storage/PolicyFilter.java | 11 +- .../java/gyro/azure/storage/PolicyRule.java | 12 +- .../gyro/azure/storage/PolicySnapshot.java | 12 +- .../azure/storage/StorageAccountFinder.java | 47 ++++- .../azure/storage/StorageAccountResource.java | 31 +-- .../gyro/azure/storage/StorageLifeCycle.java | 74 ++++--- 23 files changed, 408 insertions(+), 824 deletions(-) delete mode 100644 examples/storage/cloud-file-directory.gyro delete mode 100644 examples/storage/cloud-file.gyro delete mode 100644 examples/storage/test-cloud-file.txt delete mode 100644 src/main/java/gyro/azure/storage/CloudFileDirectoryResource.java delete mode 100644 src/main/java/gyro/azure/storage/CloudFileResource.java diff --git a/build.gradle b/build.gradle index 06f4469c..a90d5b62 100644 --- a/build.gradle +++ b/build.gradle @@ -78,6 +78,10 @@ dependencies { implementation 'com.azure.resourcemanager:azure-resourcemanager:2.14.0' implementation 'com.azure:azure-security-keyvault-certificates:4.3.1' + implementation 'com.azure:azure-data-tables:12.3.0' + implementation 'com.azure:azure-storage-queue:12.12.2' + implementation 'com.azure:azure-storage-file-share:12.12.2' + implementation 'com.azure:azure-storage-blob:12.16.1' implementation 'com.azure:azure-identity:1.5.0' implementation 'com.azure:azure-core-http-okhttp:1.8.0' runtimeOnly 'com.nimbusds:oauth2-oidc-sdk:9.34' diff --git a/examples/storage/cloud-blob-container.gyro b/examples/storage/cloud-blob-container.gyro index 0b93b46e..a8fd55ec 100644 --- a/examples/storage/cloud-blob-container.gyro +++ b/examples/storage/cloud-blob-container.gyro @@ -8,15 +8,19 @@ end azure::storage-account blob-storage-account-example resource-group: $(azure::resource-group blob-resource-group) - name: "testblobexample" + name: "testblobexampledj" tags: { - Name: "testblobexample" + Name: "testblobexampledj" } end azure::cloud-blob-container blob-container-example name: "blobcontainerexample" - public-access: "Container" + public-access: "container" storage-account: $(azure::storage-account blob-storage-account-example) + + metadata: { + Name: blob-container-example + } end diff --git a/examples/storage/cloud-blob.gyro b/examples/storage/cloud-blob.gyro index ec7b738b..5e1dc0f3 100644 --- a/examples/storage/cloud-blob.gyro +++ b/examples/storage/cloud-blob.gyro @@ -26,13 +26,12 @@ end azure::cloud-blob-container blob-container-example name: "blobcontainer" - public-access: "CONTAINER" + public-access: "container" storage-account: $(azure::storage-account blob-storage-account-example) end azure::cloud-blob blob-example - blob-directory-path: "/path/to/blob" + blob-path: "path/to/blob" container: $(azure::cloud-blob-container blob-container-example) file-path: "test-blob-doc.txt" - storage-account: $(azure::storage-account blob-storage-account-example) end diff --git a/examples/storage/cloud-file-directory.gyro b/examples/storage/cloud-file-directory.gyro deleted file mode 100644 index 1cf87810..00000000 --- a/examples/storage/cloud-file-directory.gyro +++ /dev/null @@ -1,36 +0,0 @@ -azure::resource-group cloud-file-resource-group-example - name: "cloud-file-resource-group" - - tags: { - Name: "cloud-file-resource-group" - } -end - -azure::storage-account cloud-file-account-example - resource-group: $(azure::resource-group cloud-file-resource-group-example) - name: "cloudfileexample" - - cors-rule - allowed-headers: ["*"] - allowed-methods: ["GET"] - allowed-origins: ["*"] - exposed-headers: ["*"] - max-age: 6 - type: "file" - end - - tags: { - Name: "cloudfileexample" - } -end - -azure::cloud-file-share cloud-file-share-example - name: "cloudfileshare" - storage-account: $(azure::storage-account cloud-file-account-example) -end - -azure::cloud-file-directory cloud-file-directory - path: "/example/directory/path" - cloud-file-share: $(azure::cloud-file-share cloud-file-share-example) - storage-account: $(azure::storage-account cloud-file-account-example) -end \ No newline at end of file diff --git a/examples/storage/cloud-file.gyro b/examples/storage/cloud-file.gyro deleted file mode 100644 index 3bfb8b73..00000000 --- a/examples/storage/cloud-file.gyro +++ /dev/null @@ -1,43 +0,0 @@ -azure::resource-group file-resource-group - name: "file-resource-group" - - tags: { - Name: "file-resource-group" - } -end - -azure::storage-account file-storage-account-example - resource-group: $(azure::resource-group file-resource-group) - name: "fileexampleoscars" - - cors-rule - allowed-headers: ["*"] - allowed-methods: ["GET"] - allowed-origins: ["*"] - exposed-headers: ["*"] - max-age: 6 - type: "file" - end - - tags: { - Name: "fileexampleoscars" - } -end - -azure::cloud-file-share cloud-file-share-example - name: "cloudfileshare" - storage-account: $(azure::storage-account file-storage-account-example) -end - -azure::cloud-file-directory cloud-file-directory - path: "/example/directory/path" - cloud-file-share: $(azure::cloud-file-share cloud-file-share-example) - storage-account: $(azure::storage-account file-storage-account-example) -end - -azure::cloud-file cloud-file-example - cloud-file-directory: $(azure::cloud-file-directory cloud-file-directory) - cloud-file-share: $(azure::cloud-file-share cloud-file-share-example) - file-path: "test-cloud-file.txt" - storage-account: $(azure::storage-account file-storage-account-example) -end diff --git a/examples/storage/test-cloud-file.txt b/examples/storage/test-cloud-file.txt deleted file mode 100644 index 7dda27f3..00000000 --- a/examples/storage/test-cloud-file.txt +++ /dev/null @@ -1 +0,0 @@ -This is a test cloud file diff --git a/src/main/java/gyro/azure/storage/CloudBlobContainerResource.java b/src/main/java/gyro/azure/storage/CloudBlobContainerResource.java index 111d1f39..4f52cf14 100644 --- a/src/main/java/gyro/azure/storage/CloudBlobContainerResource.java +++ b/src/main/java/gyro/azure/storage/CloudBlobContainerResource.java @@ -16,26 +16,26 @@ package gyro.azure.storage; -import com.azure.resourcemanager.storage.models.BlobContainer; -import com.azure.resourcemanager.storage.models.PublicAccess; -import com.azure.resourcemanager.storage.models.StorageAccount; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import com.azure.storage.blob.BlobContainerClient; +import com.azure.storage.blob.BlobServiceClient; +import com.azure.storage.blob.BlobServiceClientBuilder; +import com.azure.storage.blob.models.PublicAccessType; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.core.GyroUI; +import gyro.core.Type; import gyro.core.resource.Id; import gyro.core.resource.Output; -import gyro.core.resource.Updatable; -import gyro.core.Type; import gyro.core.resource.Resource; - +import gyro.core.resource.Updatable; import gyro.core.scope.State; import gyro.core.validation.Required; import gyro.core.validation.ValidStrings; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - /** * Creates a blob container * @@ -46,12 +46,12 @@ * * azure::cloud-blob-container blob-container-example * name: "blobcontainer" - * public-access: "Container" + * public-access: "container" * storage-account: $(azure::storage-account blob-storage-account-example) * end */ @Type("cloud-blob-container") -public class CloudBlobContainerResource extends AzureResource implements Copyable { +public class CloudBlobContainerResource extends AzureResource implements Copyable { private String name; private String publicAccess; @@ -73,10 +73,10 @@ public void setName(String name) { } /** - * The public access of the container. Valid values are ``Blob`` or ``Container`` or ``None`` + * The public access of the container. */ @Required - @ValidStrings({"Blob", "Container", "None"}) + @ValidStrings({ "blob", "container" }) @Updatable public String getPublicAccess() { return publicAccess; @@ -98,6 +98,7 @@ public void setStorageAccount(StorageAccountResource storageAccount) { this.storageAccount = storageAccount; } + @Updatable public Map getMetadata() { if (metadata == null) { metadata = new HashMap<>(); @@ -123,26 +124,18 @@ public void setId(String id) { } @Override - public void copyFrom(BlobContainer container) { - setPublicAccess(container.publicAccess() != null ? container.publicAccess().toString() : "None"); - setName(container.name()); - setId(container.id()); - setMetadata(container.metadata()); - - String storageAccountName = getId() - .split("Microsoft.Storage/storageAccounts/")[1] - .split("/blobServices")[0]; - setStorageAccount(findById(StorageAccountResource.class, storageAccountName)); + public void copyFrom(BlobContainerClient container) { + setPublicAccess(container.getAccessPolicy().getBlobAccessType().toString()); + setName(container.getBlobContainerName()); + setMetadata(container.getProperties().getMetadata()); + setStorageAccount(findById(StorageAccountResource.class, container.getAccountName())); } @Override public boolean refresh() { - StorageAccount storageAccount = getStorageAccount().getStorageAccount(); - - BlobContainer blobContainer = storageAccount.manager().blobContainers() - .get(storageAccount.resourceGroupName(), storageAccount.name(), getName()); + BlobContainerClient blobContainer = blobContainer(); - if (blobContainer == null) { + if (!blobContainer.exists()) { return false; } @@ -153,47 +146,46 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - StorageAccount storageAccount = getStorageAccount().getStorageAccount(); + BlobContainerClient blobContainer = blobContainer(); - BlobContainer.DefinitionStages.WithCreate withCreate = storageAccount.manager().blobContainers() - .defineContainer(getName()) - .withExistingStorageAccount(storageAccount) - .withPublicAccess(PublicAccess.fromString(getPublicAccess())); + blobContainer.create(); + + blobContainer = blobContainer(); + + blobContainer.setAccessPolicy(PublicAccessType.fromString(getPublicAccess()), null); if (!getMetadata().isEmpty()) { - withCreate.withMetadata(getMetadata()); + blobContainer.setMetadata(getMetadata()); } - BlobContainer blobContainer = withCreate.create(); - copyFrom(blobContainer); } @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) { - StorageAccount storageAccount = getStorageAccount().getStorageAccount(); - - BlobContainer blobContainer = storageAccount.manager().blobContainers() - .get(storageAccount.resourceGroupName(), storageAccount.name(), getName()); - - BlobContainer.Update update = blobContainer.update(); + BlobContainerClient blobContainer = blobContainer(); if (changedFieldNames.contains("metadata")) { - update = update.withMetadata(getMetadata()); + blobContainer.setMetadata(getMetadata()); } if (changedFieldNames.contains("public-access")) { - update = update.withPublicAccess(PublicAccess.fromString(getPublicAccess())); + blobContainer.setAccessPolicy(PublicAccessType.fromString(getPublicAccess()), null); } - - update.apply(); } @Override public void delete(GyroUI ui, State state) { - StorageAccount storageAccount = getStorageAccount().getStorageAccount(); + BlobContainerClient blobContainer = blobContainer(); + + blobContainer.delete(); + } + + protected BlobContainerClient blobContainer() { + BlobServiceClient client = new BlobServiceClientBuilder() + .connectionString(getStorageAccount().getConnection()) + .buildClient(); - storageAccount.manager().blobContainers() - .delete(storageAccount.resourceGroupName(), storageAccount.name(), getName()); + return client.getBlobContainerClient(getName()); } } diff --git a/src/main/java/gyro/azure/storage/CloudBlobResource.java b/src/main/java/gyro/azure/storage/CloudBlobResource.java index ebd4a32c..e584fad2 100644 --- a/src/main/java/gyro/azure/storage/CloudBlobResource.java +++ b/src/main/java/gyro/azure/storage/CloudBlobResource.java @@ -16,32 +16,21 @@ package gyro.azure.storage; +import java.io.BufferedInputStream; +import java.util.Set; + +import com.azure.storage.blob.BlobClient; +import com.azure.storage.blob.BlobContainerClient; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.core.GyroException; import gyro.core.GyroInputStream; import gyro.core.GyroUI; import gyro.core.Type; -import gyro.core.resource.Resource; -import com.microsoft.azure.storage.CloudStorageAccount; -import com.microsoft.azure.storage.StorageException; -import com.microsoft.azure.storage.blob.CloudBlobClient; -import com.microsoft.azure.storage.blob.CloudBlobContainer; -import com.microsoft.azure.storage.blob.CloudBlobDirectory; -import com.microsoft.azure.storage.blob.CloudBlockBlob; import gyro.core.resource.Output; +import gyro.core.resource.Resource; import gyro.core.scope.State; import gyro.core.validation.Required; -import org.apache.commons.lang.StringUtils; - -import java.io.IOException; -import java.net.URISyntaxException; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.security.InvalidKeyException; -import java.util.Iterator; -import java.util.Set; - /** * Creates a cloud blob @@ -52,35 +41,29 @@ * .. code-block:: gyro * * azure::cloud-blob blob-example - * blob-directory-path: "/path/to/blob" + * blob-path: "/path/to/blob" * container: $(azure::cloud-blob-container blob-container-example) * file-path: "test-blob-doc.txt" - * storage-account: $(azure::storage-account blob-storage-account-example) * end */ @Type("cloud-blob") -public class CloudBlobResource extends AzureResource implements Copyable { +public class CloudBlobResource extends AzureResource implements Copyable { - private String blobDirectoryPath; + private String blobPath; private CloudBlobContainerResource container; private String filePath; - private StorageAccountResource storageAccount; private String uri; /** * The directory path of the Blob. */ @Required - public String getBlobDirectoryPath() { - if (blobDirectoryPath != null && !blobDirectoryPath.startsWith("/")) { - blobDirectoryPath = "/" + blobDirectoryPath; - } - - return blobDirectoryPath; + public String getBlobPath() { + return blobPath; } - public void setBlobDirectoryPath(String blobDirectoryPath) { - this.blobDirectoryPath = blobDirectoryPath; + public void setBlobPath(String blobPath) { + this.blobPath = blobPath; } /** @@ -107,18 +90,6 @@ public void setFilePath(String filePath) { this.filePath = filePath; } - /** - * The Storage Account where the Blob will be created. - */ - @Required - public StorageAccountResource getStorageAccount() { - return storageAccount; - } - - public void setStorageAccount(StorageAccountResource storageAccount) { - this.storageAccount = storageAccount; - } - /** * The fully qualified uri of the Blob. */ @@ -132,12 +103,11 @@ public void setUri(String uri) { } @Override - public void copyFrom(CloudBlockBlob blob) { + public void copyFrom(BlobClient blob) { try { - setUri(blob.getUri().toString()); - setBlobDirectoryPath(blob.getName()); - setContainer(findById(CloudBlobContainerResource.class, blob.getContainer().getName())); - setStorageAccount(findById(StorageAccountResource.class, blob.getContainer().getStorageUri().getPrimaryUri().getAuthority().split(".blob.core")[0])); + setUri(blob.getBlobUrl()); + setBlobPath(blob.getBlobName()); + setContainer(findById(CloudBlobContainerResource.class, blob.getContainerName())); } catch (Exception ex) { throw new GyroException(ex.getMessage()); } @@ -145,26 +115,26 @@ public void copyFrom(CloudBlockBlob blob) { @Override public boolean refresh() { - try { - CloudBlockBlob blob = cloudBlobBlob(); - if (!blob.exists()) { - return false; - } + BlobClient blob = blob(); + if (!blob.exists()) { + return false; + } - copyFrom(blob); + copyFrom(blob); - return true; - } catch (StorageException | URISyntaxException | InvalidKeyException ex) { - throw new GyroException(ex.getMessage()); - } + return true; } @Override - public void create(GyroUI ui, State state) throws StorageException, URISyntaxException, InvalidKeyException, IOException { - CloudBlockBlob blob = cloudBlobBlob(); - GyroInputStream file = openInput(getFilePath()); - blob.upload(file, file.available()); - setUri(blob.getUri().toString()); + public void create(GyroUI ui, State state) { + BlobClient blob = blob(); + + try (GyroInputStream inputStream = openInput(getFilePath())) { + blob.upload(new BufferedInputStream(inputStream), inputStream.available()); + } + + blob = blob(); + setUri(blob.getBlobUrl()); } @Override @@ -173,34 +143,14 @@ public void update(GyroUI ui, State state, Resource current, Set changed } @Override - public void delete(GyroUI ui, State state) throws StorageException, URISyntaxException, InvalidKeyException { - CloudBlockBlob blob = cloudBlobBlob(); + public void delete(GyroUI ui, State state) { + BlobClient blob = blob(); blob.delete(); } - private CloudBlockBlob cloudBlobBlob() throws StorageException, URISyntaxException, InvalidKeyException { - CloudStorageAccount account = CloudStorageAccount.parse(getStorageAccount().getConnection()); - CloudBlobClient client = account.createCloudBlobClient(); - CloudBlobContainer container = client.getContainerReference(getContainer().getName()); - - if (StringUtils.countMatches(getBlobDirectoryPath(), "/") > 1) { - CloudBlobDirectory directory = createDirectories(); - return directory.getBlockBlobReference(getBlobDirectoryPath().substring(getBlobDirectoryPath().lastIndexOf("/") + 1)); - } else { - return container.getBlockBlobReference(getBlobDirectoryPath().substring(getBlobDirectoryPath().lastIndexOf("/") + 1)); - } - } + private BlobClient blob() { + BlobContainerClient client = getContainer().blobContainer(); - private CloudBlobDirectory createDirectories() throws StorageException, URISyntaxException, InvalidKeyException { - CloudStorageAccount account = CloudStorageAccount.parse(getStorageAccount().getConnection()); - CloudBlobClient client = account.createCloudBlobClient(); - CloudBlobContainer container = client.getContainerReference(getContainer().getName()); - Path directoryPath = Paths.get(getBlobDirectoryPath()).getParent(); - Iterator iter = directoryPath.iterator(); - CloudBlobDirectory directory = container.getDirectoryReference(iter.next().toString()); - while (iter.hasNext()) { - directory = directory.getDirectoryReference(iter.next().toString()); - } - return directory; + return client.getBlobClient(getBlobPath()); } } diff --git a/src/main/java/gyro/azure/storage/CloudFileDirectoryResource.java b/src/main/java/gyro/azure/storage/CloudFileDirectoryResource.java deleted file mode 100644 index 994f006b..00000000 --- a/src/main/java/gyro/azure/storage/CloudFileDirectoryResource.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Copyright 2019, Perfect Sense, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package gyro.azure.storage; - -import gyro.azure.AzureResource; -import gyro.azure.Copyable; -import gyro.core.GyroException; -import gyro.core.GyroUI; -import gyro.core.Type; -import gyro.core.resource.Id; -import gyro.core.resource.Output; -import gyro.core.resource.Resource; - -import com.microsoft.azure.storage.CloudStorageAccount; -import com.microsoft.azure.storage.StorageException; - -import com.microsoft.azure.storage.file.CloudFileClient; -import com.microsoft.azure.storage.file.CloudFileDirectory; -import com.microsoft.azure.storage.file.CloudFileShare; -import gyro.core.scope.State; -import gyro.core.validation.Required; - -import java.net.URISyntaxException; -import java.security.InvalidKeyException; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Set; - -/** - * Creates a cloud file directory - * - * Example - * ------- - * - * .. code-block:: gyro - * - * azure::cloud-file-directory cloud-file-directory - * path: "/example/directory/path" - * cloud-file-share: $(azure::cloud-file-share cloud-file-share-example) - * storage-account: $(azure::storage-account blob-storage-account-example) - * end - */ -@Type("cloud-file-directory") -public class CloudFileDirectoryResource extends AzureResource implements Copyable { - - private String path; - private String name; - private CloudFileShareResource cloudFileShare; - private StorageAccountResource storageAccount; - - /** - * The Cloud File Directory path. - */ - @Required - @Id - public String getPath() { - if (path != null && !path.startsWith("/")) { - path = "/" + path; - } - - return path; - } - - public void setPath(String path) { - this.path = path; - } - - /** - * The name of the Cloud File Directory. - */ - @Output - public String getName() { - return Paths.get(getPath()).getFileName().toString(); - } - - public void setName(String name) { - this.name = name; - } - - /** - * The Cloud File Share under which the Cloud File Directory resides. - */ - @Required - public CloudFileShareResource getCloudFileShare() { - return cloudFileShare; - } - - public void setCloudFileShare(CloudFileShareResource cloudFileShare) { - this.cloudFileShare = cloudFileShare; - } - - /** - * The Storage Account where the Cloud File Directory will be created. - */ - @Required - public StorageAccountResource getStorageAccount() { - return storageAccount; - } - - public void setStorageAccount(StorageAccountResource storageAccount) { - this.storageAccount = storageAccount; - } - - @Override - public void copyFrom(CloudFileDirectory directory) { - try { - setStorageAccount(findById(StorageAccountResource.class, directory.getStorageUri().getPrimaryUri().getAuthority().split(".file.core")[0])); - setPath(directory.getStorageUri().getPrimaryUri().getPath().split(directory.getShare().getName())[1]); - setName(directory.getName()); - setCloudFileShare(findById(CloudFileShareResource.class, directory.getShare().getName())); - } catch (Exception ex) { - throw new GyroException(ex.getMessage()); - } - } - - @Override - public boolean refresh() { - try { - CloudFileDirectory directory = cloudFileDirectory(); - if (!directory.exists()) { - return false; - } - - copyFrom(directory); - - return true; - } catch (StorageException | URISyntaxException | InvalidKeyException ex) { - throw new GyroException(ex.getMessage()); - } - } - - @Override - public void create(GyroUI ui, State state) throws StorageException, URISyntaxException, InvalidKeyException { - CloudFileDirectory directory = cloudFileDirectory(); - directory.create(); - } - - @Override - public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) { - - } - - @Override - public void delete(GyroUI ui, State state) throws StorageException, URISyntaxException, InvalidKeyException { - CloudFileDirectory directory = cloudFileDirectory(); - directory.delete(); - } - - private CloudFileDirectory cloudFileDirectory() throws StorageException, URISyntaxException, InvalidKeyException { - CloudStorageAccount storageAccount = CloudStorageAccount.parse(getStorageAccount().getConnection()); - CloudFileClient fileClient = storageAccount.createCloudFileClient(); - CloudFileShare share = fileClient.getShareReference(getCloudFileShare().getName()); - - CloudFileDirectory rootDirectory = share.getRootDirectoryReference(); - - Path cloudFilePath = Paths.get(getPath()).getParent(); - String finalDirectory = Paths.get(getPath()).getFileName().toString(); - for (Path path : cloudFilePath) { - String currentDirectory = path.toString(); - rootDirectory = rootDirectory.getDirectoryReference(currentDirectory); - rootDirectory.createIfNotExists(); - } - return rootDirectory.getDirectoryReference(finalDirectory); - } -} diff --git a/src/main/java/gyro/azure/storage/CloudFileResource.java b/src/main/java/gyro/azure/storage/CloudFileResource.java deleted file mode 100644 index 71777882..00000000 --- a/src/main/java/gyro/azure/storage/CloudFileResource.java +++ /dev/null @@ -1,196 +0,0 @@ -/* - * Copyright 2019, Perfect Sense, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package gyro.azure.storage; - -import com.microsoft.azure.storage.CloudStorageAccount; -import com.microsoft.azure.storage.file.CloudFileClient; -import com.microsoft.azure.storage.file.CloudFileShare; -import gyro.azure.AzureResource; -import gyro.azure.Copyable; -import gyro.core.GyroException; -import gyro.core.GyroInputStream; -import gyro.core.GyroUI; -import gyro.core.Type; -import gyro.core.resource.Output; -import gyro.core.resource.Resource; - -import com.microsoft.azure.storage.StorageException; -import com.microsoft.azure.storage.file.CloudFile; -import com.microsoft.azure.storage.file.CloudFileDirectory; -import gyro.core.scope.State; -import gyro.core.validation.Required; - -import java.io.IOException; -import java.net.URISyntaxException; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.security.InvalidKeyException; -import java.util.Set; - -/** - * Creates a cloud file - * - * Example - * ------- - * - * .. code-block:: gyro - * - * azure::cloud-file cloud-file-example - * cloud-file-directory: $(azure::cloud-file-directory cloud-file-directory) - * cloud-file-share: $(azure::cloud-file-share cloud-file-share-example) - * file-path: "test-cloud-file.txt" - * storage-account: $(azure::storage-account blob-storage-account-example) - * end - */ -@Type("cloud-file") -public class CloudFileResource extends AzureResource implements Copyable { - - private CloudFileDirectoryResource cloudFileDirectory; - private CloudFileShareResource cloudFileShare; - private String filePath; - private String fileName; - private StorageAccountResource storageAccount; - - /** - * The Cloud File Directory for the file. - */ - @Required - public CloudFileDirectoryResource getCloudFileDirectory() { - return cloudFileDirectory; - } - - public void setCloudFileDirectory(CloudFileDirectoryResource cloudFileDirectory) { - this.cloudFileDirectory = cloudFileDirectory; - } - - /** - * The Cloud File Share for the file. - */ - @Required - public CloudFileShareResource getCloudFileShare() { - return cloudFileShare; - } - - public void setCloudFileShare(CloudFileShareResource cloudFileShare) { - this.cloudFileShare = cloudFileShare; - } - - /** - * The path of the file to upload. - */ - @Required - public String getFilePath() { - return filePath; - } - - public void setFilePath(String filePath) { - this.filePath = filePath; - } - - /** - * The name of the file. - */ - @Output - public String getFileName() { - return fileName; - } - - public void setFileName(String fileName) { - this.fileName = fileName; - } - - /** - * The Storage Account where the file will be created. - */ - @Required - public StorageAccountResource getStorageAccount() { - return storageAccount; - } - - public void setStorageAccount(StorageAccountResource storageAccount) { - this.storageAccount = storageAccount; - } - - @Override - public void copyFrom(CloudFile file) { - try { - setStorageAccount(findById(StorageAccountResource.class, file.getStorageUri().getPrimaryUri().getAuthority().split(".file.core")[0])); - setCloudFileDirectory(findById(CloudFileDirectoryResource.class, file.getParent().getStorageUri().getPrimaryUri().getPath().split(file.getParent().getShare().getName())[1])); - setCloudFileShare(findById(CloudFileShareResource.class, file.getShare().getName())); - setFileName(file.getName()); - } catch (Exception ex) { - throw new GyroException(ex.getMessage()); - } - } - - @Override - public boolean refresh() { - try { - CloudFile file = cloudFile(); - if (!file.exists()) { - return false; - } - - copyFrom(file); - - return true; - } catch (StorageException | URISyntaxException | InvalidKeyException ex) { - throw new GyroException(ex.getMessage()); - } - } - - @Override - public void create(GyroUI ui, State state) throws StorageException, URISyntaxException, InvalidKeyException, IOException { - GyroInputStream inputStream = openInput(getFilePath()); - CloudFile file = cloudFile(); - file.upload(inputStream, inputStream.available()); - } - - @Override - public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) { - - } - - @Override - public void delete(GyroUI ui, State state) throws StorageException, URISyntaxException, InvalidKeyException { - CloudFile file = cloudFile(); - file.delete(); - } - - private CloudFile cloudFile() throws StorageException, URISyntaxException, InvalidKeyException { - String name = Paths.get(getFilePath()).getFileName().toString(); - CloudFileDirectory root = cloudFileDirectory(); - return root.getFileReference(name); - } - - private CloudFileDirectory cloudFileDirectory() throws StorageException, URISyntaxException, InvalidKeyException { - CloudStorageAccount storageAccount = CloudStorageAccount.parse(getStorageAccount().getConnection()); - CloudFileClient fileClient = storageAccount.createCloudFileClient(); - CloudFileShare share = fileClient.getShareReference(getCloudFileShare().getName()); - - CloudFileDirectory rootDirectory = share.getRootDirectoryReference(); - - Path cloudFilePath = Paths.get(getCloudFileDirectory().getPath()).getParent(); - String finalDirectory = Paths.get(getCloudFileDirectory().getPath()).getFileName().toString(); - for (Path path : cloudFilePath) { - String currentDirectory = path.toString(); - rootDirectory = rootDirectory.getDirectoryReference(currentDirectory); - rootDirectory.createIfNotExists(); - } - return rootDirectory.getDirectoryReference(finalDirectory); - } -} diff --git a/src/main/java/gyro/azure/storage/CloudFileShareResource.java b/src/main/java/gyro/azure/storage/CloudFileShareResource.java index dcf2b31b..d511411c 100644 --- a/src/main/java/gyro/azure/storage/CloudFileShareResource.java +++ b/src/main/java/gyro/azure/storage/CloudFileShareResource.java @@ -16,27 +16,23 @@ package gyro.azure.storage; +import java.util.Set; + +import com.azure.storage.file.share.ShareClient; +import com.azure.storage.file.share.ShareServiceClient; +import com.azure.storage.file.share.ShareServiceClientBuilder; +import com.azure.storage.file.share.models.ShareStorageException; +import com.azure.storage.file.share.options.ShareSetPropertiesOptions; import gyro.azure.AzureResource; import gyro.azure.Copyable; -import gyro.core.GyroException; import gyro.core.GyroUI; -import gyro.core.resource.Id; -import gyro.core.resource.Updatable; import gyro.core.Type; +import gyro.core.resource.Id; import gyro.core.resource.Resource; - -import com.microsoft.azure.storage.file.CloudFileClient; -import com.microsoft.azure.storage.file.CloudFileShare; -import com.microsoft.azure.storage.file.FileShareProperties; -import com.microsoft.azure.storage.CloudStorageAccount; -import com.microsoft.azure.storage.StorageException; +import gyro.core.resource.Updatable; import gyro.core.scope.State; import gyro.core.validation.Required; -import java.net.URISyntaxException; -import java.security.InvalidKeyException; -import java.util.Set; - /** * Creates a cloud file share * @@ -52,7 +48,7 @@ * end */ @Type("cloud-file-share") -public class CloudFileShareResource extends AzureResource implements Copyable { +public class CloudFileShareResource extends AzureResource implements Copyable { private String name; private Integer shareQuota; @@ -96,54 +92,66 @@ public void setStorageAccount(StorageAccountResource storageAccount) { } @Override - public void copyFrom(CloudFileShare share) { - setName(share.getName()); - setShareQuota(share.getProperties().getShareQuota()); - setStorageAccount(findById(StorageAccountResource.class, share.getStorageUri().getPrimaryUri().getAuthority().split(".file.core")[0])); + public void copyFrom(ShareClient share) { + setName(share.getShareName()); + setShareQuota(share.getProperties().getQuota()); + setStorageAccount(findById(StorageAccountResource.class, share.getAccountName())); } @Override public boolean refresh() { - try { - CloudFileShare share = cloudFileShare(); - if (!share.exists()) { - return false; - } + ShareClient share = verifiedCloudFileShare(); + if (share == null) { + return false; + } - copyFrom(share); + copyFrom(share); - return true; - } catch (StorageException | URISyntaxException | InvalidKeyException ex) { - throw new GyroException(ex.getMessage()); - } + return true; } @Override - public void create(GyroUI ui, State state) throws StorageException, URISyntaxException, InvalidKeyException { - CloudFileShare share = cloudFileShare(); + public void create(GyroUI ui, State state) { + ShareClient share = cloudFileShare(); share.create(); - FileShareProperties fileShareProperties = new FileShareProperties(); - fileShareProperties.setShareQuota(getShareQuota()); - share.setProperties(fileShareProperties); + + ShareSetPropertiesOptions options = new ShareSetPropertiesOptions(); + options.setQuotaInGb(getShareQuota()); + share.setProperties(options); } @Override - public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) throws StorageException, URISyntaxException, InvalidKeyException { - CloudFileShare share = cloudFileShare(); - FileShareProperties fileShareProperties = new FileShareProperties(); - fileShareProperties.setShareQuota(getShareQuota()); - share.setProperties(fileShareProperties); + public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) { + ShareClient share = cloudFileShare(); + + ShareSetPropertiesOptions options = new ShareSetPropertiesOptions(); + options.setQuotaInGb(getShareQuota()); + share.setProperties(options); } @Override - public void delete(GyroUI ui, State state) throws StorageException, URISyntaxException, InvalidKeyException { - CloudFileShare share = cloudFileShare(); + public void delete(GyroUI ui, State state) { + ShareClient share = cloudFileShare(); share.delete(); } - private CloudFileShare cloudFileShare() throws StorageException, URISyntaxException, InvalidKeyException { - CloudStorageAccount storageAccount = CloudStorageAccount.parse(getStorageAccount().getConnection()); - CloudFileClient fileClient = storageAccount.createCloudFileClient(); - return fileClient.getShareReference(getName()); + private ShareClient cloudFileShare() { + ShareServiceClient client = new ShareServiceClientBuilder() + .connectionString(getStorageAccount().getConnection()) + .buildClient(); + + return client.getShareClient(getName()); + } + + private ShareClient verifiedCloudFileShare() { + ShareClient shareClient = cloudFileShare(); + + try { + shareClient.getProperties(); + } catch (ShareStorageException ex) { + shareClient = null; + } + + return shareClient; } } diff --git a/src/main/java/gyro/azure/storage/CloudQueueResource.java b/src/main/java/gyro/azure/storage/CloudQueueResource.java index 99c13f02..32ce7856 100644 --- a/src/main/java/gyro/azure/storage/CloudQueueResource.java +++ b/src/main/java/gyro/azure/storage/CloudQueueResource.java @@ -16,26 +16,21 @@ package gyro.azure.storage; -import gyro.azure.AzureResource; +import java.util.Set; +import com.azure.storage.queue.QueueClient; +import com.azure.storage.queue.QueueServiceClient; +import com.azure.storage.queue.QueueServiceClientBuilder; +import com.azure.storage.queue.models.QueueStorageException; +import gyro.azure.AzureResource; import gyro.azure.Copyable; -import gyro.core.GyroException; import gyro.core.GyroUI; import gyro.core.Type; import gyro.core.resource.Output; import gyro.core.resource.Resource; - -import com.microsoft.azure.storage.CloudStorageAccount; -import com.microsoft.azure.storage.StorageException; -import com.microsoft.azure.storage.queue.CloudQueueClient; -import com.microsoft.azure.storage.queue.CloudQueue; import gyro.core.scope.State; import gyro.core.validation.Required; -import java.net.URISyntaxException; -import java.security.InvalidKeyException; -import java.util.Set; - /** * Creates a cloud queue * @@ -50,7 +45,7 @@ * end */ @Type("cloud-queue") -public class CloudQueueResource extends AzureResource implements Copyable { +public class CloudQueueResource extends AzureResource implements Copyable { private String name; private StorageAccountResource storageAccount; @@ -93,33 +88,29 @@ public void setId(String id) { } @Override - public void copyFrom(CloudQueue queue) { - setName(queue.getName()); - setStorageAccount(findById(StorageAccountResource.class, queue.getStorageUri().getPrimaryUri().getAuthority().split(".queue.core")[0])); - setId(String.format("%s/queueServices/default/queues/%s",getStorageAccount().getId(),getName())); + public void copyFrom(QueueClient queue) { + setName(queue.getQueueName()); + setStorageAccount(findById(StorageAccountResource.class, queue.getAccountName())); + setId(String.format("%s/queueServices/default/queues/%s", getStorageAccount().getId(), getName())); } @Override public boolean refresh() { - try { - CloudQueue queue = cloudQueue(); - if (!queue.exists()) { - return false; - } + QueueClient queue = verifiedCloudQueue(); + if (queue == null) { + return false; + } - copyFrom(queue); + copyFrom(queue); - return true; - } catch (StorageException | URISyntaxException | InvalidKeyException ex) { - throw new GyroException(ex.getMessage()); - } + return true; } @Override - public void create(GyroUI ui, State state) throws StorageException, URISyntaxException, InvalidKeyException { - CloudQueue queue = cloudQueue(); - queue.create(); - setId(String.format("%s/queueServices/default/queues/%s",getStorageAccount().getId(),getName())); + public void create(GyroUI ui, State state) { + QueueClient queueClient = cloudQueue(); + queueClient.create(); + setId(String.format("%s/queueServices/default/queues/%s", getStorageAccount().getId(), getName())); } @Override @@ -128,14 +119,36 @@ public void update(GyroUI ui, State state, Resource current, Set changed } @Override - public void delete(GyroUI ui, State state) throws StorageException, URISyntaxException, InvalidKeyException { - CloudQueue queue = cloudQueue(); - queue.delete(); + public void delete(GyroUI ui, State state) { + QueueClient queueClient = cloudQueue(); + queueClient.delete(); + } + + private QueueClient cloudQueue() { + QueueServiceClient client = new QueueServiceClientBuilder() + .connectionString(getStorageAccount().getConnection()) + .buildClient(); + + QueueClient queueClient = client.getQueueClient(getName()); + + try { + queueClient.getProperties(); + } catch (QueueStorageException ex) { + queueClient = null; + } + + return queueClient; } - private CloudQueue cloudQueue() throws StorageException, URISyntaxException, InvalidKeyException { - CloudStorageAccount storageAccount = CloudStorageAccount.parse(getStorageAccount().getConnection()); - CloudQueueClient queueClient = storageAccount.createCloudQueueClient(); - return queueClient.getQueueReference(getName()); + private QueueClient verifiedCloudQueue() { + QueueClient queueClient = cloudQueue(); + + try { + queueClient.getProperties(); + } catch (QueueStorageException ex) { + queueClient = null; + } + + return queueClient; } } diff --git a/src/main/java/gyro/azure/storage/CloudTableResource.java b/src/main/java/gyro/azure/storage/CloudTableResource.java index bdf3e5df..d4bd6afe 100644 --- a/src/main/java/gyro/azure/storage/CloudTableResource.java +++ b/src/main/java/gyro/azure/storage/CloudTableResource.java @@ -16,25 +16,20 @@ package gyro.azure.storage; -import gyro.azure.AzureResource; +import java.util.Set; +import com.azure.data.tables.TableClient; +import com.azure.data.tables.TableServiceClient; +import com.azure.data.tables.TableServiceClientBuilder; +import com.azure.data.tables.models.TableServiceException; +import gyro.azure.AzureResource; import gyro.azure.Copyable; -import gyro.core.GyroException; import gyro.core.GyroUI; import gyro.core.Type; import gyro.core.resource.Resource; - -import com.microsoft.azure.storage.CloudStorageAccount; -import com.microsoft.azure.storage.StorageException; -import com.microsoft.azure.storage.table.CloudTable; -import com.microsoft.azure.storage.table.CloudTableClient; import gyro.core.scope.State; import gyro.core.validation.Required; -import java.net.URISyntaxException; -import java.security.InvalidKeyException; -import java.util.Set; - /** * Creates a cloud table * @@ -49,7 +44,7 @@ * end */ @Type("cloud-table") -public class CloudTableResource extends AzureResource implements Copyable { +public class CloudTableResource extends AzureResource implements Copyable { private String name; private StorageAccountResource storageAccount; @@ -79,31 +74,27 @@ public void setStorageAccount(StorageAccountResource storageAccount) { } @Override - public void copyFrom(CloudTable cloudTable) { - setName(cloudTable.getName()); - setStorageAccount(findById(StorageAccountResource.class, cloudTable.getStorageUri().getPrimaryUri().getAuthority().split(".table.core")[0])); + public void copyFrom(TableClient cloudTable) { + setName(cloudTable.getTableName()); + setStorageAccount(findById(StorageAccountResource.class, cloudTable.getAccountName())); } @Override public boolean refresh() { - try { - CloudTable cloudTable = cloudTable(); - if (!cloudTable.exists()) { - return false; - } + TableClient tableClient = verifiedCloudTable(); + if (tableClient == null) { + return false; + } - copyFrom(cloudTable); + copyFrom(tableClient); - return true; - } catch (StorageException | URISyntaxException | InvalidKeyException ex) { - throw new GyroException(ex.getMessage()); - } + return true; } @Override - public void create(GyroUI ui, State state) throws StorageException, URISyntaxException, InvalidKeyException { - CloudTable cloudTable = cloudTable(); - cloudTable.create(); + public void create(GyroUI ui, State state) { + TableClient tableClient = cloudTable(); + tableClient.createTable(); } @Override @@ -112,14 +103,36 @@ public void update(GyroUI ui, State state, Resource current, Set changed } @Override - public void delete(GyroUI ui, State state) throws StorageException, URISyntaxException, InvalidKeyException { - CloudTable cloudTable = cloudTable(); - cloudTable.delete(); + public void delete(GyroUI ui, State state) { + TableClient tableClient = cloudTable(); + tableClient.deleteTable(); + } + + private TableClient cloudTable() { + TableServiceClient client = new TableServiceClientBuilder() + .connectionString(getStorageAccount().getConnection()) + .buildClient(); + + TableClient tableClient = client.getTableClient(getName()); + + try { + tableClient.getAccessPolicies(); + } catch (TableServiceException ex) { + tableClient = null; + } + + return tableClient; } - private CloudTable cloudTable() throws StorageException, URISyntaxException, InvalidKeyException { - CloudStorageAccount account = CloudStorageAccount.parse(getStorageAccount().getConnection()); - CloudTableClient tableClient = account.createCloudTableClient(); - return tableClient.getTableReference(getName()); + private TableClient verifiedCloudTable() { + TableClient tableClient = cloudTable(); + + try { + tableClient.getAccessPolicies(); + } catch (TableServiceException ex) { + tableClient = null; + } + + return tableClient; } } diff --git a/src/main/java/gyro/azure/storage/Cors.java b/src/main/java/gyro/azure/storage/Cors.java index 931edc70..3a1f9b06 100644 --- a/src/main/java/gyro/azure/storage/Cors.java +++ b/src/main/java/gyro/azure/storage/Cors.java @@ -16,20 +16,19 @@ package gyro.azure.storage; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Set; +import java.util.stream.Collectors; + +import com.azure.resourcemanager.storage.models.CorsRule; +import com.azure.resourcemanager.storage.models.CorsRuleAllowedMethodsItem; import gyro.azure.Copyable; import gyro.core.resource.Diffable; import gyro.core.resource.Updatable; - -import com.microsoft.azure.storage.CorsHttpMethods; -import com.microsoft.azure.storage.CorsRule; import gyro.core.validation.Required; import gyro.core.validation.ValidStrings; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.EnumSet; -import java.util.Set; - /** * Creates a cors rule * @@ -140,7 +139,7 @@ public void setMaxAge(Integer maxAge) { * Specifies which service the rule belongs to. */ @Required - @ValidStrings({"blob", "file", "queue", "table"}) + @ValidStrings({ "blob", "file", "queue", "table" }) public String getType() { return type; } @@ -151,11 +150,11 @@ public void setType(String type) { @Override public void copyFrom(CorsRule rule) { - setAllowedHeaders(new HashSet<>(rule.getAllowedHeaders())); - setAllowedOrigins(new HashSet<>(rule.getAllowedOrigins())); - rule.getAllowedMethods().forEach(r -> getAllowedMethods().add(r.name())); - setExposedHeaders(new HashSet<>(rule.getExposedHeaders())); - setMaxAge(rule.getMaxAgeInSeconds()); + setAllowedHeaders(new HashSet<>(rule.allowedHeaders())); + setAllowedOrigins(new HashSet<>(rule.allowedOrigins())); + rule.allowedMethods().forEach(r -> getAllowedMethods().add(r.toString())); + setExposedHeaders(new HashSet<>(rule.exposedHeaders())); + setMaxAge(rule.maxAgeInSeconds()); } public String primaryKey() { @@ -166,22 +165,13 @@ public String primaryKey() { public CorsRule toCors() { CorsRule rule = new CorsRule(); - rule.setAllowedHeaders(new ArrayList<>(getAllowedHeaders())); - rule.setAllowedMethods(toAllowedMethods()); - rule.setAllowedOrigins(new ArrayList<>(getAllowedOrigins())); - rule.setExposedHeaders(new ArrayList<>(getExposedHeaders())); - rule.setMaxAgeInSeconds(getMaxAge()); + rule.withAllowedHeaders(new ArrayList<>(getAllowedHeaders())); + rule.withAllowedMethods(getAllowedMethods().stream() + .map(CorsRuleAllowedMethodsItem::fromString).collect(Collectors.toList())); + rule.withAllowedOrigins(new ArrayList<>(getAllowedOrigins())); + rule.withExposedHeaders(new ArrayList<>(getExposedHeaders())); + rule.withMaxAgeInSeconds(getMaxAge()); return rule; } - - private EnumSet toAllowedMethods() { - EnumSet httpMethods = null; - - for (String method : getAllowedMethods()) { - httpMethods = EnumSet.of(CorsHttpMethods.valueOf(method)); - } - - return httpMethods; - } } diff --git a/src/main/java/gyro/azure/storage/PolicyAction.java b/src/main/java/gyro/azure/storage/PolicyAction.java index 815ac540..2174070e 100644 --- a/src/main/java/gyro/azure/storage/PolicyAction.java +++ b/src/main/java/gyro/azure/storage/PolicyAction.java @@ -16,13 +16,14 @@ package gyro.azure.storage; -import com.microsoft.azure.management.storage.ManagementPolicyAction; +import com.azure.resourcemanager.storage.models.ManagementPolicyAction; import gyro.azure.Copyable; import gyro.core.resource.Diffable; import gyro.core.resource.Updatable; import gyro.core.validation.Required; public class PolicyAction extends Diffable implements Copyable { + private PolicyBaseBlob baseBlob; private PolicySnapshot snapshot; diff --git a/src/main/java/gyro/azure/storage/PolicyBaseBlob.java b/src/main/java/gyro/azure/storage/PolicyBaseBlob.java index 8becc602..654ef33f 100644 --- a/src/main/java/gyro/azure/storage/PolicyBaseBlob.java +++ b/src/main/java/gyro/azure/storage/PolicyBaseBlob.java @@ -16,17 +16,18 @@ package gyro.azure.storage; -import com.microsoft.azure.management.storage.DateAfterModification; -import com.microsoft.azure.management.storage.ManagementPolicyBaseBlob; +import java.util.ArrayList; +import java.util.List; + +import com.azure.resourcemanager.storage.models.DateAfterModification; +import com.azure.resourcemanager.storage.models.ManagementPolicyBaseBlob; import gyro.azure.Copyable; import gyro.core.resource.Diffable; import gyro.core.resource.Updatable; import gyro.core.validation.ValidationError; -import java.util.ArrayList; -import java.util.List; - public class PolicyBaseBlob extends Diffable implements Copyable { + private Double deleteDays; private Double tierToArchiveDays; private Double tierToCoolDays; @@ -74,23 +75,30 @@ public String primaryKey() { @Override public void copyFrom(ManagementPolicyBaseBlob policyBaseBlob) { - setDeleteDays(policyBaseBlob.delete() != null ? policyBaseBlob.delete().daysAfterModificationGreaterThan() : null); - setTierToArchiveDays(policyBaseBlob.tierToArchive() != null ? policyBaseBlob.tierToArchive().daysAfterModificationGreaterThan() : null); - setTierToCoolDays(policyBaseBlob.tierToCool() != null ? policyBaseBlob.tierToCool().daysAfterModificationGreaterThan() : null); + setDeleteDays(policyBaseBlob.delete() != null + ? (double) policyBaseBlob.delete().daysAfterModificationGreaterThan() + : null); + setTierToArchiveDays(policyBaseBlob.tierToArchive() != null ? (double) policyBaseBlob.tierToArchive() + .daysAfterModificationGreaterThan() : null); + setTierToCoolDays(policyBaseBlob.tierToCool() != null ? (double) policyBaseBlob.tierToCool() + .daysAfterModificationGreaterThan() : null); } ManagementPolicyBaseBlob toManagementPolicyBaseBlob() { ManagementPolicyBaseBlob blob = new ManagementPolicyBaseBlob(); if (getDeleteDays() != null) { - blob.withDelete(new DateAfterModification().withDaysAfterModificationGreaterThan(getDeleteDays())); + blob.withDelete(new DateAfterModification().withDaysAfterModificationGreaterThan(Float.parseFloat( + getDeleteDays().toString()))); } if (getTierToArchiveDays() != null) { - blob.withTierToArchive(new DateAfterModification().withDaysAfterModificationGreaterThan(getTierToArchiveDays())); + blob.withTierToArchive(new DateAfterModification().withDaysAfterModificationGreaterThan(Float.parseFloat( + getTierToArchiveDays().toString()))); } if (getTierToCoolDays() != null) { - blob.withTierToCool(new DateAfterModification().withDaysAfterModificationGreaterThan(getTierToCoolDays())); + blob.withTierToCool(new DateAfterModification().withDaysAfterModificationGreaterThan(Float.parseFloat( + getTierToCoolDays().toString()))); } return blob; @@ -101,7 +109,10 @@ public List validate() { List errors = new ArrayList<>(); if (getDeleteDays() == null && getTierToCoolDays() == null && getTierToArchiveDays() == null) { - errors.add(new ValidationError(this, null, "At least one of 'delete-days' or 'tier-to-cool-days' or 'tier-to-archive-days' is required.")); + errors.add(new ValidationError( + this, + null, + "At least one of 'delete-days' or 'tier-to-cool-days' or 'tier-to-archive-days' is required.")); } return errors; diff --git a/src/main/java/gyro/azure/storage/PolicyDefinition.java b/src/main/java/gyro/azure/storage/PolicyDefinition.java index 8f49ef05..72525c6b 100644 --- a/src/main/java/gyro/azure/storage/PolicyDefinition.java +++ b/src/main/java/gyro/azure/storage/PolicyDefinition.java @@ -16,13 +16,14 @@ package gyro.azure.storage; -import com.microsoft.azure.management.storage.ManagementPolicyDefinition; +import com.azure.resourcemanager.storage.models.ManagementPolicyDefinition; import gyro.azure.Copyable; import gyro.core.resource.Diffable; import gyro.core.resource.Updatable; import gyro.core.validation.Required; public class PolicyDefinition extends Diffable implements Copyable { + private PolicyAction action; private PolicyFilter filter; diff --git a/src/main/java/gyro/azure/storage/PolicyFilter.java b/src/main/java/gyro/azure/storage/PolicyFilter.java index 24327910..0a8b012b 100644 --- a/src/main/java/gyro/azure/storage/PolicyFilter.java +++ b/src/main/java/gyro/azure/storage/PolicyFilter.java @@ -16,16 +16,17 @@ package gyro.azure.storage; -import com.microsoft.azure.management.storage.ManagementPolicyFilter; -import gyro.azure.Copyable; -import gyro.core.resource.Diffable; -import gyro.core.resource.Updatable; - import java.util.ArrayList; import java.util.HashSet; import java.util.Set; +import com.azure.resourcemanager.storage.models.ManagementPolicyFilter; +import gyro.azure.Copyable; +import gyro.core.resource.Diffable; +import gyro.core.resource.Updatable; + public class PolicyFilter extends Diffable implements Copyable { + private Set blobTypes; private Set prefixMatches; diff --git a/src/main/java/gyro/azure/storage/PolicyRule.java b/src/main/java/gyro/azure/storage/PolicyRule.java index 830eb084..0981e89c 100644 --- a/src/main/java/gyro/azure/storage/PolicyRule.java +++ b/src/main/java/gyro/azure/storage/PolicyRule.java @@ -16,15 +16,17 @@ package gyro.azure.storage; -import com.microsoft.azure.management.storage.ManagementPolicyRule; +import com.azure.resourcemanager.storage.models.ManagementPolicyRule; +import com.azure.resourcemanager.storage.models.RuleType; import gyro.azure.Copyable; import gyro.core.resource.Diffable; import gyro.core.resource.Updatable; import gyro.core.validation.Required; public class PolicyRule extends Diffable implements Copyable { + private String name; - private String type; + private RuleType type; private Boolean enabled; private PolicyDefinition definition; @@ -43,15 +45,15 @@ public void setName(String name) { /** * Type of rule. Currently only supported value is ``Lifecycle``. Defaults to ``Lifecycle``. */ - public String getType() { + public RuleType getType() { if (type == null) { - type = "Lifecycle"; + type = RuleType.LIFECYCLE; } return type; } - public void setType(String type) { + public void setType(RuleType type) { this.type = type; } diff --git a/src/main/java/gyro/azure/storage/PolicySnapshot.java b/src/main/java/gyro/azure/storage/PolicySnapshot.java index 347e6053..99443fcc 100644 --- a/src/main/java/gyro/azure/storage/PolicySnapshot.java +++ b/src/main/java/gyro/azure/storage/PolicySnapshot.java @@ -16,14 +16,15 @@ package gyro.azure.storage; -import com.microsoft.azure.management.storage.DateAfterCreation; -import com.microsoft.azure.management.storage.ManagementPolicySnapShot; +import com.azure.resourcemanager.storage.models.DateAfterCreation; +import com.azure.resourcemanager.storage.models.ManagementPolicySnapShot; import gyro.azure.Copyable; import gyro.core.resource.Diffable; import gyro.core.resource.Updatable; import gyro.core.validation.Required; public class PolicySnapshot extends Diffable implements Copyable { + private Double deleteDays; /** @@ -46,13 +47,16 @@ public String primaryKey() { @Override public void copyFrom(ManagementPolicySnapShot policySnapShot) { - setDeleteDays(policySnapShot.delete() != null ? policySnapShot.delete().daysAfterCreationGreaterThan() : null); + setDeleteDays(policySnapShot.delete() != null + ? (double) policySnapShot.delete().daysAfterCreationGreaterThan() + : null); } ManagementPolicySnapShot toManagementPolicySnapShot() { ManagementPolicySnapShot snapShot = new ManagementPolicySnapShot(); if (getDeleteDays() != null) { - snapShot.withDelete(new DateAfterCreation().withDaysAfterCreationGreaterThan(getDeleteDays())); + snapShot.withDelete(new DateAfterCreation() + .withDaysAfterCreationGreaterThan(Float.parseFloat(getDeleteDays().toString()))); } return snapShot; diff --git a/src/main/java/gyro/azure/storage/StorageAccountFinder.java b/src/main/java/gyro/azure/storage/StorageAccountFinder.java index b99b7d8c..0349dc40 100644 --- a/src/main/java/gyro/azure/storage/StorageAccountFinder.java +++ b/src/main/java/gyro/azure/storage/StorageAccountFinder.java @@ -16,19 +16,23 @@ package gyro.azure.storage; -import com.azure.resourcemanager.AzureResourceManager; -import com.azure.resourcemanager.storage.models.StorageAccount; -import gyro.azure.AzureResourceManagerFinder; -import gyro.core.Type; - import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.storage.models.StorageAccount; +import gyro.azure.AzureResourceManagerFinder; +import gyro.core.GyroException; +import gyro.core.Type; + @Type("storage-account") public class StorageAccountFinder extends AzureResourceManagerFinder { + private String id; + private String resourceGroup; + private String name; /** * The ID of the Storage Account. @@ -41,6 +45,28 @@ public void setId(String id) { this.id = id; } + /** + * The name of the resource group the Storage Account belongs. + */ + public String getResourceGroup() { + return resourceGroup; + } + + public void setResourceGroup(String resourceGroup) { + this.resourceGroup = resourceGroup; + } + + /** + * The name of the Storage Account. + */ + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + @Override protected List findAllAzure(AzureResourceManager client) { return client.storageAccounts().list().stream().collect(Collectors.toList()); @@ -48,7 +74,16 @@ protected List findAllAzure(AzureResourceManager client) { @Override protected List findAzure(AzureResourceManager client, Map filters) { - StorageAccount storageAccount = client.storageAccounts().getById(filters.get("id")); + StorageAccount storageAccount; + if (filters.containsKey("id")) { + storageAccount = client.storageAccounts().getById(filters.get("id")); + } else if (filters.containsKey("resource-group") && filters.containsKey("name")) { + storageAccount = client.storageAccounts() + .getByResourceGroup(filters.get("resource-group"), filters.get("name")); + } else { + throw new GyroException("Either 'id' or both of 'resource-group' and 'name' is required"); + } + if (storageAccount == null) { return Collections.emptyList(); } else { diff --git a/src/main/java/gyro/azure/storage/StorageAccountResource.java b/src/main/java/gyro/azure/storage/StorageAccountResource.java index 5dd257e2..f76e2a68 100644 --- a/src/main/java/gyro/azure/storage/StorageAccountResource.java +++ b/src/main/java/gyro/azure/storage/StorageAccountResource.java @@ -16,6 +16,13 @@ package gyro.azure.storage; +import java.net.URISyntaxException; +import java.security.InvalidKeyException; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + import com.azure.core.management.Region; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.storage.models.Kind; @@ -25,21 +32,14 @@ import gyro.azure.resources.ResourceGroupResource; import gyro.core.GyroException; import gyro.core.GyroUI; -import gyro.core.resource.Id; -import gyro.core.resource.Updatable; import gyro.core.Type; +import gyro.core.resource.Id; import gyro.core.resource.Output; import gyro.core.resource.Resource; +import gyro.core.resource.Updatable; import gyro.core.scope.State; import gyro.core.validation.Required; -import java.net.URISyntaxException; -import java.security.InvalidKeyException; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - /** * Creates a storage account * @@ -220,7 +220,8 @@ public void copyFrom(StorageAccount storageAccount) { public boolean refresh() { AzureResourceManager client = createResourceManagerClient(); - StorageAccount storageAccount = client.storageAccounts().getByResourceGroup(getResourceGroup().getName(), getName()); + StorageAccount storageAccount = client.storageAccounts() + .getByResourceGroup(getResourceGroup().getName(), getName()); if (storageAccount == null) { return false; @@ -253,7 +254,8 @@ public void create(GyroUI ui, State state) throws URISyntaxException, InvalidKey } @Override - public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) throws URISyntaxException, InvalidKeyException { + public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) + throws URISyntaxException, InvalidKeyException { AzureResourceManager client = createResourceManagerClient(); StorageAccount storageAccount = client.storageAccounts().getById(getId()); @@ -280,9 +282,10 @@ public void delete(GyroUI ui, State state) { } public String getConnection() { - return "DefaultEndpointsProtocol=https;" - + "AccountName=" + getName() + ";" - + "AccountKey=" + keys().get("key1"); + return String.format("DefaultEndpointsProtocol=https;" + + "AccountName=%s;" + + "AccountKey=%s;" + + "EndpointSuffix=core.windows.net", getName(), keys().get("key1")); } public Map keys() { diff --git a/src/main/java/gyro/azure/storage/StorageLifeCycle.java b/src/main/java/gyro/azure/storage/StorageLifeCycle.java index f0f11dbb..7e158d64 100644 --- a/src/main/java/gyro/azure/storage/StorageLifeCycle.java +++ b/src/main/java/gyro/azure/storage/StorageLifeCycle.java @@ -16,14 +16,18 @@ package gyro.azure.storage; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.storage.BlobTypes; -import com.microsoft.azure.management.storage.ManagementPolicy; -import com.microsoft.azure.management.storage.ManagementPolicyRule; -import com.microsoft.azure.management.storage.ManagementPolicySchema; -import com.microsoft.azure.management.storage.StorageAccount; -import com.microsoft.azure.management.storage.PolicyRule.DefinitionStages.WithBlobTypesToFilterFor; -import com.microsoft.azure.management.storage.PolicyRule.DefinitionStages.WithPolicyRuleAttachable; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashSet; +import java.util.Set; +import java.util.stream.Collectors; + +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.storage.models.BlobTypes; +import com.azure.resourcemanager.storage.models.ManagementPolicy; +import com.azure.resourcemanager.storage.models.ManagementPolicyRule; +import com.azure.resourcemanager.storage.models.ManagementPolicySchema; +import com.azure.resourcemanager.storage.models.StorageAccount; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.core.GyroException; @@ -35,13 +39,8 @@ import gyro.core.validation.Required; import gyro.core.validation.ValidStrings; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashSet; -import java.util.Set; -import java.util.stream.Collectors; - public class StorageLifeCycle extends AzureResource implements Copyable { + private String name; private String id; private Date lastModified; @@ -115,7 +114,7 @@ public String primaryKey() { public void copyFrom(ManagementPolicy policy) { setName(policy.name()); setId(policy.id()); - setLastModified(policy.lastModifiedTime().toDate()); + setLastModified(Date.from(policy.lastModifiedTime().toInstant())); getRule().clear(); for (ManagementPolicyRule rule : policy.policy().rules()) { @@ -132,33 +131,45 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) throws Exception { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); StorageAccountResource parent = (StorageAccountResource) parent(); if (!parent.getUpgradeAccountV2()) { - throw new GyroException("Cannot create lifecycle for a storage account not of 'General Purpose Account Kind V2'."); + throw new GyroException( + "Cannot create lifecycle for a storage account not of 'General Purpose Account Kind V2'."); } StorageAccount storageAccount = client.storageAccounts().getById(parent.getId()); - ManagementPolicy.DefinitionStages.WithRule withRule = storageAccount.manager().managementPolicies().define(getName()) + ManagementPolicy.DefinitionStages.WithRule withRule = storageAccount.manager() + .managementPolicies() + .define(getName()) .withExistingStorageAccount(parent.getResourceGroup().getName(), parent.getName()); ManagementPolicy.DefinitionStages.WithCreate create = null; for (PolicyRule rule : getRule()) { - WithBlobTypesToFilterFor withBlobTypesToFilterFor = create == null - ? withRule.defineRule(rule.getName()).withLifecycleRuleType() - : create.defineRule(rule.getName()).withLifecycleRuleType(); - - WithPolicyRuleAttachable withPolicyRuleAttachable = withBlobTypesToFilterFor - .withBlobTypesToFilterFor(rule.getDefinition().getFilter().getBlobTypes().stream().map(BlobTypes::fromString).collect(Collectors.toList())) + com.azure.resourcemanager.storage.models.PolicyRule.DefinitionStages.WithBlobTypesToFilterFor withBlobTypesToFilterFor = + create == null + ? withRule.defineRule(rule.getName()).withLifecycleRuleType() + : create.defineRule(rule.getName()).withLifecycleRuleType(); + + com.azure.resourcemanager.storage.models.PolicyRule.DefinitionStages.WithPolicyRuleAttachable withPolicyRuleAttachable = withBlobTypesToFilterFor + .withBlobTypesToFilterFor(rule.getDefinition() + .getFilter() + .getBlobTypes() + .stream() + .map(BlobTypes::fromString) + .collect(Collectors.toList())) .withPrefixesToFilterFor(new ArrayList<>(rule.getDefinition().getFilter().getPrefixMatches())) .withActionsOnBaseBlob(rule.getDefinition().getAction().getBaseBlob().toManagementPolicyBaseBlob()); if (rule.getDefinition().getAction().getSnapshot() != null) { - create = withPolicyRuleAttachable.withActionsOnSnapShot(rule.getDefinition().getAction().getSnapshot().toManagementPolicySnapShot()).attach(); + create = withPolicyRuleAttachable.withActionsOnSnapShot(rule.getDefinition() + .getAction() + .getSnapshot() + .toManagementPolicySnapShot()).attach(); } else { create = withPolicyRuleAttachable.attach(); } @@ -179,7 +190,7 @@ public void create(GyroUI ui, State state) throws Exception { @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); ManagementPolicySchema policySchema = new ManagementPolicySchema(); policySchema.withRules(getRule().stream().map(PolicyRule::toManagementPolicyRule).collect(Collectors.toList())); @@ -192,25 +203,22 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); StorageAccountResource parent = (StorageAccountResource) parent(); StorageAccount storageAccount = client.storageAccounts().getById(parent.getId()); storageAccount.manager() .managementPolicies() - .inner() - .delete(parent.getResourceGroup().getName(), parent.getName()); + .deleteAsync(parent.getResourceGroup().getName(), parent.getName()).block(); } - private ManagementPolicy getManagementPolicy(Azure client) { + private ManagementPolicy getManagementPolicy(AzureResourceManager client) { StorageAccountResource parent = (StorageAccountResource) parent(); StorageAccount storageAccount = client.storageAccounts().getById(parent.getId()); return storageAccount.manager() .managementPolicies() - .getAsync(parent.getResourceGroup().getName(), parent.getName()) - .toBlocking() - .single(); + .getAsync(parent.getResourceGroup().getName(), parent.getName()).block(); } } From 94a9f1de1fd9e9a4d328e94aa135590f4fe51d7b Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Fri, 27 May 2022 16:29:03 -0400 Subject: [PATCH 34/43] initial cosmosdb refactor --- .../azure/cosmosdb/CosmosDBAccountFinder.java | 15 ++++++----- .../cosmosdb/CosmosDBAccountResource.java | 26 +++++++++---------- 2 files changed, 21 insertions(+), 20 deletions(-) diff --git a/src/main/java/gyro/azure/cosmosdb/CosmosDBAccountFinder.java b/src/main/java/gyro/azure/cosmosdb/CosmosDBAccountFinder.java index 5cc570b1..ce519826 100644 --- a/src/main/java/gyro/azure/cosmosdb/CosmosDBAccountFinder.java +++ b/src/main/java/gyro/azure/cosmosdb/CosmosDBAccountFinder.java @@ -16,14 +16,15 @@ package gyro.azure.cosmosdb; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.cosmosdb.CosmosDBAccount; -import gyro.azure.AzureFinder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.cosmos.models.CosmosDBAccount; +import gyro.azure.AzureResourceManagerFinder; import gyro.core.Type; import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; /** * Query cosmos db. @@ -36,7 +37,7 @@ * cosmos-db: $(external-query azure::cosmos-db {}) */ @Type("cosmos-db") -public class CosmosDBAccountFinder extends AzureFinder { +public class CosmosDBAccountFinder extends AzureResourceManagerFinder { private String id; /** @@ -51,12 +52,12 @@ public void setId(String id) { } @Override - protected List findAllAzure(Azure client) { - return client.cosmosDBAccounts().list(); + protected List findAllAzure(AzureResourceManager client) { + return client.cosmosDBAccounts().list().stream().collect(Collectors.toList()); } @Override - protected List findAzure(Azure client, Map filters) { + protected List findAzure(AzureResourceManager client, Map filters) { CosmosDBAccount cosmosDBAccount = client.cosmosDBAccounts().getById(filters.get("id")); if (cosmosDBAccount == null) { return Collections.emptyList(); diff --git a/src/main/java/gyro/azure/cosmosdb/CosmosDBAccountResource.java b/src/main/java/gyro/azure/cosmosdb/CosmosDBAccountResource.java index 368c6456..aa0cd213 100644 --- a/src/main/java/gyro/azure/cosmosdb/CosmosDBAccountResource.java +++ b/src/main/java/gyro/azure/cosmosdb/CosmosDBAccountResource.java @@ -16,6 +16,11 @@ package gyro.azure.cosmosdb; +import com.azure.core.management.Region; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.cosmos.models.CosmosDBAccount; +import com.azure.resourcemanager.cosmos.models.Location; +import com.azure.resourcemanager.cosmos.models.VirtualNetworkRule; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.azure.resources.ResourceGroupResource; @@ -26,15 +31,10 @@ import gyro.core.Type; import gyro.core.resource.Updatable; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.cosmosdb.CosmosDBAccount; -import com.microsoft.azure.management.cosmosdb.Location; -import com.microsoft.azure.management.cosmosdb.VirtualNetworkRule; -import com.microsoft.azure.management.cosmosdb.CosmosDBAccount.DefinitionStages.WithCreate; -import com.microsoft.azure.management.cosmosdb.CosmosDBAccount.DefinitionStages.WithConsistencyPolicy; -import com.microsoft.azure.management.cosmosdb.CosmosDBAccount.DefinitionStages.WithKind; -import com.microsoft.azure.management.cosmosdb.CosmosDBAccount.UpdateStages.WithOptionals; -import com.microsoft.azure.management.resources.fluentcore.arm.Region; +import com.azure.resourcemanager.cosmos.models.CosmosDBAccount.DefinitionStages.WithCreate; +import com.azure.resourcemanager.cosmos.models.CosmosDBAccount.DefinitionStages.WithConsistencyPolicy; +import com.azure.resourcemanager.cosmos.models.CosmosDBAccount.DefinitionStages.WithKind; +import com.azure.resourcemanager.cosmos.models.CosmosDBAccount.UpdateStages.WithOptionals; import gyro.core.scope.State; import gyro.core.validation.Range; import gyro.core.validation.Required; @@ -287,7 +287,7 @@ public void copyFrom(CosmosDBAccount cosmosAccount) { @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); CosmosDBAccount cosmosAccount = client.cosmosDBAccounts().getById(getId()); @@ -302,7 +302,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); WithKind withKind = client.cosmosDBAccounts() .define(getName()) @@ -357,7 +357,7 @@ && getMaxInterval() != null) { @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); CosmosDBAccount.Update update = client.cosmosDBAccounts() .getById(getId()) @@ -417,7 +417,7 @@ && getMaxInterval() != null) { @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); client.cosmosDBAccounts().deleteById(getId()); } From 8298c8c746107cb58571ee28332b4ebb183bca32 Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Fri, 27 May 2022 18:00:55 -0400 Subject: [PATCH 35/43] initial network refactor --- .../java/gyro/azure/AbstractAzureCommand.java | 15 ++ .../AbstractApplicationGatewayCommand.java | 27 +++- .../network/AbstractHealthCheckProbe.java | 1 + ...dApplicationGatewayCertificateCommand.java | 4 +- .../network/ApplicationGatewayFinder.java | 21 +-- ...licationGatewayManagedServiceIdentity.java | 10 +- .../network/ApplicationGatewayResource.java | 129 ++++++++++-------- .../ApplicationSecurityGroupFinder.java | 24 ++-- .../ApplicationSecurityGroupResource.java | 32 ++--- src/main/java/gyro/azure/network/Backend.java | 35 +++-- .../network/BackendHttpConfiguration.java | 12 +- .../azure/network/HealthCheckProbeHttp.java | 4 +- .../azure/network/HealthCheckProbeTcp.java | 3 +- .../gyro/azure/network/InboundNatPool.java | 9 +- .../gyro/azure/network/InboundNatRule.java | 9 +- ...tApplicationGatewayCertificateCommand.java | 6 +- .../java/gyro/azure/network/Listener.java | 7 +- .../azure/network/ListenerSslCertificate.java | 2 +- .../azure/network/LoadBalancerFinder.java | 20 +-- .../azure/network/LoadBalancerResource.java | 114 +++++++++------- .../gyro/azure/network/LoadBalancerRule.java | 6 +- .../gyro/azure/network/NetworkFinder.java | 11 +- .../azure/network/NetworkInterfaceFinder.java | 20 +-- .../network/NetworkInterfaceResource.java | 66 +++++---- .../gyro/azure/network/NetworkResource.java | 20 +-- .../network/NetworkSecurityGroupFinder.java | 22 +-- .../network/NetworkSecurityGroupResource.java | 29 ++-- .../NetworkSecurityGroupRuleResource.java | 54 ++++---- .../java/gyro/azure/network/NicBackend.java | 3 +- .../network/NicIpConfigurationResource.java | 67 +++++---- .../java/gyro/azure/network/NicNatRule.java | 4 +- .../gyro/azure/network/PrivateFrontend.java | 6 +- src/main/java/gyro/azure/network/Probe.java | 24 ++-- .../gyro/azure/network/PublicFrontend.java | 5 +- .../azure/network/PublicIpAddressFinder.java | 11 +- .../network/PublicIpAddressResource.java | 30 ++-- .../azure/network/RedirectConfiguration.java | 20 +-- ...eApplicationGatewayCertificateCommand.java | 6 +- .../azure/network/RequestRoutingRule.java | 20 +-- .../gyro/azure/network/RouteResource.java | 7 +- .../gyro/azure/network/RouteTableFinder.java | 21 +-- .../azure/network/RouteTableResource.java | 39 +++--- .../gyro/azure/network/SubnetResource.java | 36 ++--- 43 files changed, 563 insertions(+), 448 deletions(-) diff --git a/src/main/java/gyro/azure/AbstractAzureCommand.java b/src/main/java/gyro/azure/AbstractAzureCommand.java index 29d28dc6..0f56ea23 100644 --- a/src/main/java/gyro/azure/AbstractAzureCommand.java +++ b/src/main/java/gyro/azure/AbstractAzureCommand.java @@ -25,6 +25,7 @@ import java.util.stream.Collectors; import java.util.stream.Stream; +import com.azure.resourcemanager.AzureResourceManager; import com.microsoft.azure.management.Azure; import gyro.core.GyroCore; import gyro.core.GyroException; @@ -99,6 +100,20 @@ public Azure getClient() { return AzureResource.createClient((AzureCredentials) credentials); } + public AzureResourceManager getResourceManagerClient() { + Credentials credentials = getScope().getSettings(CredentialsSettings.class) + .getCredentialsByName() + .get("azure::" + getCredential()); + + if (credentials == null) { + throw new GyroException(String.format( + "No credentials with name - '%s' found. Check the your project init file.", + getCredential())); + } + + return AzureResource.createResourceManagerClient((AzureCredentials) credentials); + } + private void evaluateFile(String file, Consumer consumer, RootScope current) { if (StringUtils.isBlank(file)) { return; diff --git a/src/main/java/gyro/azure/network/AbstractApplicationGatewayCommand.java b/src/main/java/gyro/azure/network/AbstractApplicationGatewayCommand.java index f193776b..79cd8803 100644 --- a/src/main/java/gyro/azure/network/AbstractApplicationGatewayCommand.java +++ b/src/main/java/gyro/azure/network/AbstractApplicationGatewayCommand.java @@ -2,6 +2,7 @@ import java.util.concurrent.Callable; +import com.azure.resourcemanager.AzureResourceManager; import com.microsoft.azure.management.Azure; import com.microsoft.azure.management.network.ApplicationGateway; import gyro.azure.AbstractAzureCommand; @@ -10,7 +11,8 @@ import gyro.core.resource.Resource; import gyro.core.scope.RootScope; -public abstract class AbstractApplicationGatewayCommand extends AbstractAzureCommand implements GyroCommand, Callable { +public abstract class AbstractApplicationGatewayCommand extends AbstractAzureCommand + implements GyroCommand, Callable { ApplicationGateway getApplicationGateway(String applicationGatewayResourceName) { RootScope scope = getScope(); @@ -35,6 +37,29 @@ ApplicationGateway getApplicationGateway(String applicationGatewayResourceName) } } + com.azure.resourcemanager.network.models.ApplicationGateway getApplicationGatewayResourceManager(String applicationGatewayResourceName) { + RootScope scope = getScope(); + + Resource resource = scope.findResource("azure::application-gateway::" + applicationGatewayResourceName); + + if (resource instanceof ApplicationGatewayResource) { + AzureResourceManager client = getResourceManagerClient(); + + com.azure.resourcemanager.network.models.ApplicationGateway applicationGateway = client.applicationGateways() + .getById(((ApplicationGatewayResource) resource).getId()); + + if (applicationGateway == null) { + throw new GyroException("The application gateway no longer exists!!"); + } + + return applicationGateway; + } else { + throw new GyroException(String.format( + "No 'application-gateway' resource found with name - %s", + applicationGatewayResourceName)); + } + } + @Override public Integer call() throws Exception { execute(); diff --git a/src/main/java/gyro/azure/network/AbstractHealthCheckProbe.java b/src/main/java/gyro/azure/network/AbstractHealthCheckProbe.java index 8b7d69f0..47c16467 100644 --- a/src/main/java/gyro/azure/network/AbstractHealthCheckProbe.java +++ b/src/main/java/gyro/azure/network/AbstractHealthCheckProbe.java @@ -21,6 +21,7 @@ import gyro.core.validation.Required; public abstract class AbstractHealthCheckProbe extends Diffable { + private String name; private Integer interval; private Integer port; diff --git a/src/main/java/gyro/azure/network/AddApplicationGatewayCertificateCommand.java b/src/main/java/gyro/azure/network/AddApplicationGatewayCertificateCommand.java index 488933e1..60af9c08 100644 --- a/src/main/java/gyro/azure/network/AddApplicationGatewayCertificateCommand.java +++ b/src/main/java/gyro/azure/network/AddApplicationGatewayCertificateCommand.java @@ -3,7 +3,7 @@ import java.io.File; import java.util.List; -import com.microsoft.azure.management.network.ApplicationGateway; +import com.azure.resourcemanager.network.models.ApplicationGateway; import com.psddev.dari.util.ObjectUtils; import gyro.core.GyroCore; import gyro.core.GyroException; @@ -32,7 +32,7 @@ public void execute() throws Exception { String certificateName = arguments.get(1); String certificatePath = arguments.get(2); - ApplicationGateway applicationGateway = getApplicationGateway(applicationGatewayResourceName); + ApplicationGateway applicationGateway = getApplicationGatewayResourceManager(applicationGatewayResourceName); applicationGateway.update().defineSslCertificate(certificateName) .withPfxFromFile(new File(certificatePath)) diff --git a/src/main/java/gyro/azure/network/ApplicationGatewayFinder.java b/src/main/java/gyro/azure/network/ApplicationGatewayFinder.java index 1fea161c..bd4b4a41 100644 --- a/src/main/java/gyro/azure/network/ApplicationGatewayFinder.java +++ b/src/main/java/gyro/azure/network/ApplicationGatewayFinder.java @@ -16,14 +16,15 @@ package gyro.azure.network; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.network.ApplicationGateway; -import gyro.azure.AzureFinder; -import gyro.core.Type; - import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; + +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.network.models.ApplicationGateway; +import gyro.azure.AzureResourceManagerFinder; +import gyro.core.Type; /** * Query application gateway. @@ -36,7 +37,9 @@ * application-gateway: $(external-query azure::application-gateway {}) */ @Type("application-gateway") -public class ApplicationGatewayFinder extends AzureFinder { +public class ApplicationGatewayFinder + extends AzureResourceManagerFinder { + private String id; /** @@ -51,12 +54,12 @@ public void setId(String id) { } @Override - protected List findAllAzure(Azure client) { - return client.applicationGateways().list(); + protected List findAllAzure(AzureResourceManager client) { + return client.applicationGateways().list().stream().collect(Collectors.toList()); } @Override - protected List findAzure(Azure client, Map filters) { + protected List findAzure(AzureResourceManager client, Map filters) { ApplicationGateway applicationGateway = client.applicationGateways().getById(filters.get("id")); if (applicationGateway == null) { return Collections.emptyList(); diff --git a/src/main/java/gyro/azure/network/ApplicationGatewayManagedServiceIdentity.java b/src/main/java/gyro/azure/network/ApplicationGatewayManagedServiceIdentity.java index 5bbee10b..4a265efe 100644 --- a/src/main/java/gyro/azure/network/ApplicationGatewayManagedServiceIdentity.java +++ b/src/main/java/gyro/azure/network/ApplicationGatewayManagedServiceIdentity.java @@ -6,9 +6,9 @@ import java.util.Map; import java.util.stream.Collectors; -import com.microsoft.azure.management.network.ManagedServiceIdentity; -import com.microsoft.azure.management.network.ManagedServiceIdentityUserAssignedIdentitiesValue; -import com.microsoft.azure.management.network.ResourceIdentityType; +import com.azure.resourcemanager.network.models.ManagedServiceIdentity; +import com.azure.resourcemanager.network.models.ManagedServiceIdentityUserAssignedIdentities; +import com.azure.resourcemanager.network.models.ResourceIdentityType; import gyro.azure.Copyable; import gyro.azure.identity.IdentityResource; import gyro.core.resource.Diffable; @@ -97,8 +97,8 @@ public String primaryKey() { } ManagedServiceIdentity toManagedServiceIdentity() { - ManagedServiceIdentityUserAssignedIdentitiesValue value = new ManagedServiceIdentityUserAssignedIdentitiesValue(); - Map map = new HashMap<>(); + ManagedServiceIdentityUserAssignedIdentities value = new ManagedServiceIdentityUserAssignedIdentities(); + Map map = new HashMap<>(); getUserAssignedIdentity().forEach(o -> map.put(o.getId(), value)); return new ManagedServiceIdentity().withType(ResourceIdentityType.USER_ASSIGNED) diff --git a/src/main/java/gyro/azure/network/ApplicationGatewayResource.java b/src/main/java/gyro/azure/network/ApplicationGatewayResource.java index 51a8587f..b14d0038 100644 --- a/src/main/java/gyro/azure/network/ApplicationGatewayResource.java +++ b/src/main/java/gyro/azure/network/ApplicationGatewayResource.java @@ -16,45 +16,45 @@ package gyro.azure.network; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.network.ApplicationGateway; -import com.microsoft.azure.management.network.ApplicationGateway.Update; -import com.microsoft.azure.management.network.ApplicationGatewayBackend; -import com.microsoft.azure.management.network.ApplicationGatewayBackendHealth; -import com.microsoft.azure.management.network.ApplicationGatewayBackendHealthStatus; -import com.microsoft.azure.management.network.ApplicationGatewayBackendHttpConfiguration; -import com.microsoft.azure.management.network.ApplicationGatewayBackendHttpConfigurationHealth; -import com.microsoft.azure.management.network.ApplicationGatewayBackendServerHealth; -import com.microsoft.azure.management.network.ApplicationGatewayListener; -import com.microsoft.azure.management.network.ApplicationGatewayProbe; -import com.microsoft.azure.management.network.ApplicationGatewayRedirectConfiguration; -import com.microsoft.azure.management.network.ApplicationGatewayRequestRoutingRule; -import com.microsoft.azure.management.network.ApplicationGatewayRequestRoutingRuleType; -import com.microsoft.azure.management.network.ApplicationGatewaySkuName; -import com.microsoft.azure.management.network.ApplicationGatewayTier; -import com.microsoft.azure.management.resources.fluentcore.arm.AvailabilityZoneId; -import com.microsoft.azure.management.resources.fluentcore.arm.Region; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import com.azure.core.management.Region; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.network.models.ApplicationGateway; +import com.azure.resourcemanager.network.models.ApplicationGateway.Update; +import com.azure.resourcemanager.network.models.ApplicationGatewayBackend; +import com.azure.resourcemanager.network.models.ApplicationGatewayBackendHealth; +import com.azure.resourcemanager.network.models.ApplicationGatewayBackendHealthStatus; +import com.azure.resourcemanager.network.models.ApplicationGatewayBackendHttpConfiguration; +import com.azure.resourcemanager.network.models.ApplicationGatewayBackendHttpConfigurationHealth; +import com.azure.resourcemanager.network.models.ApplicationGatewayBackendServerHealth; +import com.azure.resourcemanager.network.models.ApplicationGatewayListener; +import com.azure.resourcemanager.network.models.ApplicationGatewayProbe; +import com.azure.resourcemanager.network.models.ApplicationGatewayRedirectConfiguration; +import com.azure.resourcemanager.network.models.ApplicationGatewayRequestRoutingRule; +import com.azure.resourcemanager.network.models.ApplicationGatewayRequestRoutingRuleType; +import com.azure.resourcemanager.network.models.ApplicationGatewaySkuName; +import com.azure.resourcemanager.network.models.ApplicationGatewayTier; +import com.azure.resourcemanager.resources.fluentcore.arm.AvailabilityZoneId; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.azure.resources.ResourceGroupResource; import gyro.core.GyroException; import gyro.core.GyroUI; -import gyro.core.resource.Id; -import gyro.core.resource.Updatable; import gyro.core.Type; +import gyro.core.resource.Id; import gyro.core.resource.Output; import gyro.core.resource.Resource; +import gyro.core.resource.Updatable; import gyro.core.scope.State; import gyro.core.validation.Required; import gyro.core.validation.ValidStrings; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - /** * Creates an Application Gateway. * @@ -212,6 +212,7 @@ */ @Type("application-gateway") public class ApplicationGatewayResource extends AzureResource implements Copyable { + private ResourceGroupResource resourceGroup; private NetworkResource network; private PublicIpAddressResource publicIpAddress; @@ -408,7 +409,14 @@ public void setProbe(Set probe) { * The SKU for the Application Gateway. */ @Required - @ValidStrings({"STANDARD_SMALL", "STANDARD_MEDIUM", "STANDARD_LARGE", "WAF_MEDIUM", "WAF_LARGE", "STANDARD_V2", "WAF_V2"}) + @ValidStrings({ + "STANDARD_SMALL", + "STANDARD_MEDIUM", + "STANDARD_LARGE", + "WAF_MEDIUM", + "WAF_LARGE", + "STANDARD_V2", + "WAF_V2" }) @Updatable public String getSkuSize() { return skuSize != null ? skuSize.toUpperCase() : null; @@ -422,12 +430,12 @@ public void setSkuSize(String skuSize) { * The SKU for the Application Gateway. */ @Required - @ValidStrings({"STANDARD", "STANDARD_V2", "WAF", "WAF_V2"}) + @ValidStrings({ "STANDARD", "STANDARD_V2", "WAF", "WAF_V2" }) @Updatable public String getSkuTier() { return skuTier != null - ? skuTier.toUpperCase() - : null; + ? skuTier.toUpperCase() + : null; } public void setSkuTier(String skuTier) { @@ -497,11 +505,11 @@ public void setPrivateFrontEnd(Boolean privateFrontEnd) { * Availability Zones this Application Gateway should be deployed to redundancy. * */ - @ValidStrings({"1", "2", "3"}) + @ValidStrings({ "1", "2", "3" }) public Set getAvailabilityZones() { return availabilityZones == null - ? availabilityZones = new HashSet<>() - : availabilityZones; + ? availabilityZones = new HashSet<>() + : availabilityZones; } public void setAvailabilityZones(Set availabilityZones) { @@ -539,7 +547,7 @@ public Map backendHealth() { Map healthMap = new HashMap<>(); int total = 0; - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); ApplicationGateway applicationGateway = client.applicationGateways().getById(getId()); if (applicationGateway != null) { @@ -582,9 +590,9 @@ public void copyFrom(ApplicationGateway applicationGateway) { setResourceGroup(findById(ResourceGroupResource.class, applicationGateway.resourceGroupName())); getAvailabilityZones().clear(); - if (applicationGateway.inner() != null - && applicationGateway.inner().zones() != null) { - for (String availabilityZone : applicationGateway.inner().zones()) { + if (applicationGateway.innerModel() != null + && applicationGateway.innerModel().zones() != null) { + for (String availabilityZone : applicationGateway.innerModel().zones()) { getAvailabilityZones().add(availabilityZone); } } @@ -604,14 +612,16 @@ public void copyFrom(ApplicationGateway applicationGateway) { } getBackendHttpConfiguration().clear(); - for (ApplicationGatewayBackendHttpConfiguration backendHttpConfig : applicationGateway.backendHttpConfigurations().values()) { + for (ApplicationGatewayBackendHttpConfiguration backendHttpConfig : applicationGateway.backendHttpConfigurations() + .values()) { BackendHttpConfiguration backendHttpConfiguration = newSubresource(BackendHttpConfiguration.class); backendHttpConfiguration.copyFrom(backendHttpConfig); getBackendHttpConfiguration().add(backendHttpConfiguration); } getRedirectConfiguration().clear(); - for (ApplicationGatewayRedirectConfiguration applicationGatewayRedirectConfig: applicationGateway.redirectConfigurations().values()) { + for (ApplicationGatewayRedirectConfiguration applicationGatewayRedirectConfig : applicationGateway.redirectConfigurations() + .values()) { RedirectConfiguration redirectConfiguration = newSubresource(RedirectConfiguration.class); redirectConfiguration.copyFrom(applicationGatewayRedirectConfig); getRedirectConfiguration().add(redirectConfiguration); @@ -625,8 +635,10 @@ public void copyFrom(ApplicationGateway applicationGateway) { } getRequestRoutingRule().clear(); - for (ApplicationGatewayRequestRoutingRule applicationGatewayRequestRoutingRule: applicationGateway.requestRoutingRules().values()) { - if (applicationGatewayRequestRoutingRule.ruleType().equals(ApplicationGatewayRequestRoutingRuleType.BASIC)) { + for (ApplicationGatewayRequestRoutingRule applicationGatewayRequestRoutingRule : applicationGateway.requestRoutingRules() + .values()) { + if (applicationGatewayRequestRoutingRule.ruleType() + .equals(ApplicationGatewayRequestRoutingRuleType.BASIC)) { RequestRoutingRule requestRoutingRule = newSubresource(RequestRoutingRule.class); requestRoutingRule.copyFrom(applicationGatewayRequestRoutingRule); getRequestRoutingRule().add(requestRoutingRule); @@ -634,16 +646,16 @@ public void copyFrom(ApplicationGateway applicationGateway) { } setManagedServiceIdentity(null); - if (applicationGateway.inner().identity() != null) { + if (applicationGateway.innerModel().identity() != null) { ApplicationGatewayManagedServiceIdentity identity = newSubresource(ApplicationGatewayManagedServiceIdentity.class); - identity.copyFrom(applicationGateway.inner().identity()); + identity.copyFrom(applicationGateway.innerModel().identity()); setManagedServiceIdentity(identity); } } @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); ApplicationGateway applicationGateway = client.applicationGateways().getById(getId()); @@ -658,7 +670,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); ApplicationGateway.DefinitionStages.WithRequestRoutingRule withRequestRoutingRule = client.applicationGateways() .define(getName()).withRegion(Region.fromName(getRegion())) @@ -689,11 +701,11 @@ public void create(GyroUI ui, State state) { withCreate = backendHttpConfiguration.createBackendHttpConfiguration(withCreate); } - for (RedirectConfiguration redirectConfiguration: getRedirectConfiguration()) { + for (RedirectConfiguration redirectConfiguration : getRedirectConfiguration()) { withCreate = redirectConfiguration.createRedirectConfiguration(withCreate); } - for (Probe probe: getProbe()) { + for (Probe probe : getProbe()) { withCreate = probe.createProbe(withCreate); } @@ -708,9 +720,9 @@ public void create(GyroUI ui, State state) { withCreate.withIdentity(getManagedServiceIdentity().toManagedServiceIdentity()); } - ApplicationGateway applicationGateway = withCreate.withExistingPublicIPAddress( - client.publicIPAddresses().getById(getPublicIpAddress().getId()) - ) + ApplicationGateway applicationGateway = withCreate.withExistingPublicIpAddress( + client.publicIpAddresses().getById(getPublicIpAddress().getId()) + ) .withInstanceCount(getInstanceCount()) .withSize(ApplicationGatewaySkuName.fromString(getSkuSize())) .withTier(ApplicationGatewayTier.fromString(getSkuTier())) @@ -723,13 +735,13 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource resource, Set changedFieldNames) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); ApplicationGateway applicationGateway = client.applicationGateways().getById(getId()); ApplicationGateway.Update update = applicationGateway.update() - .withSize(ApplicationGatewaySkuName.fromString(getSkuSize())) - .withTier(ApplicationGatewayTier.fromString(getSkuTier())); + .withSize(ApplicationGatewaySkuName.fromString(getSkuSize())) + .withTier(ApplicationGatewayTier.fromString(getSkuTier())); ApplicationGatewayResource oldApplicationGatewayResource = (ApplicationGatewayResource) resource; @@ -747,7 +759,6 @@ public void update(GyroUI ui, State state, Resource resource, Set change update = saveRequestRoutingRule(oldApplicationGatewayResource.getRequestRoutingRule(), update); - if (changedFieldNames.contains("managed-service-identity")) { if (getManagedServiceIdentity() == null) { throw new GyroException("Cannot unset 'managed-service-identity'."); @@ -763,7 +774,7 @@ public void update(GyroUI ui, State state, Resource resource, Set change @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); client.applicationGateways().deleteById(getId()); } @@ -873,7 +884,9 @@ private Update saveRedirectConfiguration(Set oldRedirectC return update; } - private Update saveBackendHttpConfiguration(Set oldBackendHttpConfigurations, Update update) { + private Update saveBackendHttpConfiguration( + Set oldBackendHttpConfigurations, + Update update) { Set backendHttpConfigurationNames = getBackendHttpConfiguration().stream() .map(BackendHttpConfiguration::getName).collect(Collectors.toSet()); @@ -992,7 +1005,7 @@ private Update saveTags(Map oldTags, Update update) { .filter(o -> !getTags().containsKey(o)) .collect(Collectors.toList()); - for (String tag: removeTags) { + for (String tag : removeTags) { update = update.withoutTag(tag); } diff --git a/src/main/java/gyro/azure/network/ApplicationSecurityGroupFinder.java b/src/main/java/gyro/azure/network/ApplicationSecurityGroupFinder.java index 9b0b2510..c16a8158 100644 --- a/src/main/java/gyro/azure/network/ApplicationSecurityGroupFinder.java +++ b/src/main/java/gyro/azure/network/ApplicationSecurityGroupFinder.java @@ -16,14 +16,15 @@ package gyro.azure.network; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.network.ApplicationSecurityGroup; -import gyro.azure.AzureFinder; -import gyro.core.Type; - import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; + +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.network.models.ApplicationSecurityGroup; +import gyro.azure.AzureResourceManagerFinder; +import gyro.core.Type; /** * Query application security group. @@ -36,7 +37,9 @@ * application-security-group: $(external-query azure::application-security-group {}) */ @Type("application-security-group") -public class ApplicationSecurityGroupFinder extends AzureFinder { +public class ApplicationSecurityGroupFinder + extends AzureResourceManagerFinder { + private String id; /** @@ -51,13 +54,14 @@ public void setId(String id) { } @Override - protected List findAllAzure(Azure client) { - return client.applicationSecurityGroups().list(); + protected List findAllAzure(AzureResourceManager client) { + return client.applicationSecurityGroups().list().stream().collect(Collectors.toList()); } @Override - protected List findAzure(Azure client, Map filters) { - ApplicationSecurityGroup applicationSecurityGroup = client.applicationSecurityGroups().getById(filters.get("id")); + protected List findAzure(AzureResourceManager client, Map filters) { + ApplicationSecurityGroup applicationSecurityGroup = client.applicationSecurityGroups() + .getById(filters.get("id")); if (applicationSecurityGroup == null) { return Collections.emptyList(); } else { diff --git a/src/main/java/gyro/azure/network/ApplicationSecurityGroupResource.java b/src/main/java/gyro/azure/network/ApplicationSecurityGroupResource.java index 22599d3b..1208b879 100644 --- a/src/main/java/gyro/azure/network/ApplicationSecurityGroupResource.java +++ b/src/main/java/gyro/azure/network/ApplicationSecurityGroupResource.java @@ -16,26 +16,25 @@ package gyro.azure.network; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import com.azure.core.management.Region; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.network.models.ApplicationSecurityGroup; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.azure.resources.ResourceGroupResource; import gyro.core.GyroUI; +import gyro.core.Type; import gyro.core.resource.Id; -import gyro.core.resource.Resource; import gyro.core.resource.Output; -import gyro.core.Type; +import gyro.core.resource.Resource; import gyro.core.resource.Updatable; - -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.network.ApplicationSecurityGroup; -import com.microsoft.azure.management.resources.fluentcore.arm.Region; import gyro.core.scope.State; import gyro.core.validation.Required; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - /** * Creates an application security group * @@ -54,6 +53,7 @@ */ @Type("application-security-group") public class ApplicationSecurityGroupResource extends AzureResource implements Copyable { + private String id; private String name; private ResourceGroupResource resourceGroup; @@ -172,15 +172,15 @@ public void copyFrom(ApplicationSecurityGroup applicationSecurityGroup) { setResourceGroup(findById(ResourceGroupResource.class, applicationSecurityGroup.resourceGroupName())); setTags(applicationSecurityGroup.tags()); - setProvisioningState(applicationSecurityGroup.provisioningState().toString()); + setProvisioningState(applicationSecurityGroup.provisioningState()); setResourceGuid(applicationSecurityGroup.resourceGuid()); - setEtag(applicationSecurityGroup.inner().etag()); + setEtag(applicationSecurityGroup.innerModel().etag()); setType(applicationSecurityGroup.type()); } @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); ApplicationSecurityGroup applicationSecurityGroup = client.applicationSecurityGroups().getById(getId()); @@ -195,7 +195,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); ApplicationSecurityGroup applicationSecurityGroup = client.applicationSecurityGroups().define(getName()) .withRegion(Region.fromName(getRegion())) @@ -208,14 +208,14 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); client.applicationSecurityGroups().getById(getId()).update().withTags(getTags()).apply(); } @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); client.applicationSecurityGroups().deleteById(getId()); } diff --git a/src/main/java/gyro/azure/network/Backend.java b/src/main/java/gyro/azure/network/Backend.java index 1c7c6db0..7ab3a52f 100644 --- a/src/main/java/gyro/azure/network/Backend.java +++ b/src/main/java/gyro/azure/network/Backend.java @@ -16,22 +16,21 @@ package gyro.azure.network; -import com.microsoft.azure.management.network.ApplicationGateway; -import com.microsoft.azure.management.network.ApplicationGateway.Update; -import com.microsoft.azure.management.network.ApplicationGatewayBackend; -import com.microsoft.azure.management.network.ApplicationGatewayBackend.UpdateDefinitionStages.WithAttach; -import com.microsoft.azure.management.network.ApplicationGateway.DefinitionStages.WithCreate; -import com.microsoft.azure.management.network.ApplicationGatewayBackendAddress; -import gyro.azure.Copyable; -import gyro.core.resource.Diffable; -import gyro.core.resource.Updatable; -import gyro.core.validation.Required; - import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; +import com.azure.resourcemanager.network.models.ApplicationGateway.DefinitionStages.WithCreate; +import com.azure.resourcemanager.network.models.ApplicationGateway.Update; +import com.azure.resourcemanager.network.models.ApplicationGatewayBackend; +import com.azure.resourcemanager.network.models.ApplicationGatewayBackend.UpdateDefinitionStages.WithAttach; +import com.azure.resourcemanager.network.models.ApplicationGatewayBackendAddress; +import gyro.azure.Copyable; +import gyro.core.resource.Diffable; +import gyro.core.resource.Updatable; +import gyro.core.validation.Required; + /** * Creates a Backend. * @@ -49,6 +48,7 @@ * end */ public class Backend extends Diffable implements Copyable { + private String name; private Set ipAddresses; private Set fqdns; @@ -100,8 +100,15 @@ public void setFqdns(Set fqdns) { @Override public void copyFrom(ApplicationGatewayBackend backend) { setName(backend.name()); - setIpAddresses(backend.addresses().stream().map(ApplicationGatewayBackendAddress::ipAddress).collect(Collectors.toSet())); - setFqdns(backend.addresses().stream().map(ApplicationGatewayBackendAddress::fqdn).filter(Objects::nonNull).collect(Collectors.toSet())); + setIpAddresses(backend.addresses() + .stream() + .map(ApplicationGatewayBackendAddress::ipAddress) + .collect(Collectors.toSet())); + setFqdns(backend.addresses() + .stream() + .map(ApplicationGatewayBackendAddress::fqdn) + .filter(Objects::nonNull) + .collect(Collectors.toSet())); } @Override @@ -124,7 +131,7 @@ WithCreate createBackend(WithCreate attach) { } Update createBackend(Update update) { - WithAttach updateWithAttach = update.defineBackend(getName()); + WithAttach updateWithAttach = update.defineBackend(getName()); for (String ipAddress : getIpAddresses()) { updateWithAttach = updateWithAttach.withIPAddress(ipAddress); diff --git a/src/main/java/gyro/azure/network/BackendHttpConfiguration.java b/src/main/java/gyro/azure/network/BackendHttpConfiguration.java index 288d80b7..4658738b 100644 --- a/src/main/java/gyro/azure/network/BackendHttpConfiguration.java +++ b/src/main/java/gyro/azure/network/BackendHttpConfiguration.java @@ -16,10 +16,10 @@ package gyro.azure.network; -import com.microsoft.azure.management.network.ApplicationGateway.Update; -import com.microsoft.azure.management.network.ApplicationGatewayBackendHttpConfiguration; -import com.microsoft.azure.management.network.ApplicationGateway.DefinitionStages.WithCreate; -import com.microsoft.azure.management.network.ApplicationGatewayBackendHttpConfiguration.DefinitionStages.WithAttach; +import com.azure.resourcemanager.network.models.ApplicationGateway.DefinitionStages.WithCreate; +import com.azure.resourcemanager.network.models.ApplicationGateway.Update; +import com.azure.resourcemanager.network.models.ApplicationGatewayBackendHttpConfiguration; +import com.azure.resourcemanager.network.models.ApplicationGatewayBackendHttpConfiguration.DefinitionStages.WithAttach; import com.psddev.dari.util.ObjectUtils; import gyro.azure.Copyable; import gyro.core.resource.Diffable; @@ -47,6 +47,7 @@ * end */ public class BackendHttpConfiguration extends Diffable implements Copyable { + private String name; private Integer port; private String cookieName; @@ -214,7 +215,8 @@ WithCreate createBackendHttpConfiguration(WithCreate attach) { } if (getConnectionDrainingTimeout() > 0) { - withCreateWithAttach = withCreateWithAttach.withConnectionDrainingTimeoutInSeconds(getConnectionDrainingTimeout()); + withCreateWithAttach = withCreateWithAttach.withConnectionDrainingTimeoutInSeconds( + getConnectionDrainingTimeout()); } if (!ObjectUtils.isBlank(getProbe())) { diff --git a/src/main/java/gyro/azure/network/HealthCheckProbeHttp.java b/src/main/java/gyro/azure/network/HealthCheckProbeHttp.java index 7b5c07ef..90242b7f 100644 --- a/src/main/java/gyro/azure/network/HealthCheckProbeHttp.java +++ b/src/main/java/gyro/azure/network/HealthCheckProbeHttp.java @@ -16,10 +16,9 @@ package gyro.azure.network; +import com.azure.resourcemanager.network.models.LoadBalancerHttpProbe; import gyro.azure.Copyable; import gyro.core.resource.Updatable; - -import com.microsoft.azure.management.network.LoadBalancerHttpProbe; import gyro.core.validation.Required; /** @@ -39,6 +38,7 @@ * end */ public class HealthCheckProbeHttp extends AbstractHealthCheckProbe implements Copyable { + private String requestPath; /** diff --git a/src/main/java/gyro/azure/network/HealthCheckProbeTcp.java b/src/main/java/gyro/azure/network/HealthCheckProbeTcp.java index a50fab47..2d904317 100644 --- a/src/main/java/gyro/azure/network/HealthCheckProbeTcp.java +++ b/src/main/java/gyro/azure/network/HealthCheckProbeTcp.java @@ -16,10 +16,9 @@ package gyro.azure.network; +import com.azure.resourcemanager.network.models.LoadBalancerTcpProbe; import gyro.azure.Copyable; -import com.microsoft.azure.management.network.LoadBalancerTcpProbe; - /** * Creates a tcp health check probe. * diff --git a/src/main/java/gyro/azure/network/InboundNatPool.java b/src/main/java/gyro/azure/network/InboundNatPool.java index 55559461..1a998cfd 100644 --- a/src/main/java/gyro/azure/network/InboundNatPool.java +++ b/src/main/java/gyro/azure/network/InboundNatPool.java @@ -16,12 +16,11 @@ package gyro.azure.network; +import com.azure.resourcemanager.network.models.LoadBalancerInboundNatPool; +import com.azure.resourcemanager.network.models.TransportProtocol; import gyro.azure.Copyable; import gyro.core.resource.Diffable; import gyro.core.resource.Updatable; - -import com.microsoft.azure.management.network.LoadBalancerInboundNatPool; -import com.microsoft.azure.management.network.TransportProtocol; import gyro.core.validation.Required; import gyro.core.validation.ValidStrings; @@ -119,7 +118,7 @@ public void setName(String name) { * The protocol used by the Inbound Nat Pool. */ @Required - @ValidStrings({"TCP", "UDP"}) + @ValidStrings({ "TCP", "UDP" }) @Updatable public String getProtocol() { return protocol; @@ -143,4 +142,4 @@ public String primaryKey() { return getName(); } -} \ No newline at end of file +} diff --git a/src/main/java/gyro/azure/network/InboundNatRule.java b/src/main/java/gyro/azure/network/InboundNatRule.java index b203a7df..5e61de53 100644 --- a/src/main/java/gyro/azure/network/InboundNatRule.java +++ b/src/main/java/gyro/azure/network/InboundNatRule.java @@ -16,12 +16,11 @@ package gyro.azure.network; +import com.azure.resourcemanager.network.models.LoadBalancerInboundNatRule; +import com.azure.resourcemanager.network.models.TransportProtocol; import gyro.azure.Copyable; import gyro.core.resource.Diffable; import gyro.core.resource.Updatable; - -import com.microsoft.azure.management.network.LoadBalancerInboundNatRule; -import com.microsoft.azure.management.network.TransportProtocol; import gyro.core.validation.Required; import gyro.core.validation.ValidStrings; @@ -120,7 +119,7 @@ public void setFrontendPort(Integer frontendPort) { * The protocol used by the Inbound Nat Rule. */ @Required - @ValidStrings({"TCP", "UDP"}) + @ValidStrings({ "TCP", "UDP" }) @Updatable public String getProtocol() { return protocol; @@ -144,4 +143,4 @@ public String primaryKey() { return getName(); } -} \ No newline at end of file +} diff --git a/src/main/java/gyro/azure/network/ListApplicationGatewayCertificateCommand.java b/src/main/java/gyro/azure/network/ListApplicationGatewayCertificateCommand.java index 4d56ecd0..9c4ddfcf 100644 --- a/src/main/java/gyro/azure/network/ListApplicationGatewayCertificateCommand.java +++ b/src/main/java/gyro/azure/network/ListApplicationGatewayCertificateCommand.java @@ -19,8 +19,8 @@ import java.util.ArrayList; import java.util.List; -import com.microsoft.azure.management.network.ApplicationGateway; -import com.microsoft.azure.management.network.ApplicationGatewaySslCertificate; +import com.azure.resourcemanager.network.models.ApplicationGateway; +import com.azure.resourcemanager.network.models.ApplicationGatewaySslCertificate; import gyro.core.GyroCore; import gyro.core.GyroException; import picocli.CommandLine.Command; @@ -49,7 +49,7 @@ public void execute() throws Exception { if (arguments.size() == 1) { String applicationGatewayResourceName = arguments.get(0); - ApplicationGateway applicationGateway = getApplicationGateway(applicationGatewayResourceName); + ApplicationGateway applicationGateway = getApplicationGatewayResourceManager(applicationGatewayResourceName); List sslCertificates = new ArrayList<>(applicationGateway.sslCertificates() .values()); diff --git a/src/main/java/gyro/azure/network/Listener.java b/src/main/java/gyro/azure/network/Listener.java index 92bb6398..37c74ed4 100644 --- a/src/main/java/gyro/azure/network/Listener.java +++ b/src/main/java/gyro/azure/network/Listener.java @@ -18,9 +18,9 @@ import java.util.Optional; -import com.microsoft.azure.management.network.ApplicationGateway.DefinitionStages.WithCreate; -import com.microsoft.azure.management.network.ApplicationGateway.Update; -import com.microsoft.azure.management.network.ApplicationGatewayListener; +import com.azure.resourcemanager.network.models.ApplicationGateway.DefinitionStages.WithCreate; +import com.azure.resourcemanager.network.models.ApplicationGateway.Update; +import com.azure.resourcemanager.network.models.ApplicationGatewayListener; import com.psddev.dari.util.ObjectUtils; import gyro.azure.Copyable; import gyro.core.resource.Diffable; @@ -41,6 +41,7 @@ * end */ public class Listener extends Diffable implements Copyable { + private String name; private Integer port; private Boolean privateFrontend; diff --git a/src/main/java/gyro/azure/network/ListenerSslCertificate.java b/src/main/java/gyro/azure/network/ListenerSslCertificate.java index c4b74ffe..38654782 100644 --- a/src/main/java/gyro/azure/network/ListenerSslCertificate.java +++ b/src/main/java/gyro/azure/network/ListenerSslCertificate.java @@ -1,6 +1,6 @@ package gyro.azure.network; -import com.microsoft.azure.management.network.ApplicationGatewaySslCertificate; +import com.azure.resourcemanager.network.models.ApplicationGatewaySslCertificate; import gyro.azure.Copyable; import gyro.core.resource.Diffable; import gyro.core.validation.Required; diff --git a/src/main/java/gyro/azure/network/LoadBalancerFinder.java b/src/main/java/gyro/azure/network/LoadBalancerFinder.java index a86a9751..9cb4f64e 100644 --- a/src/main/java/gyro/azure/network/LoadBalancerFinder.java +++ b/src/main/java/gyro/azure/network/LoadBalancerFinder.java @@ -16,14 +16,15 @@ package gyro.azure.network; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.network.LoadBalancer; -import gyro.azure.AzureFinder; -import gyro.core.Type; - import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; + +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.network.models.LoadBalancer; +import gyro.azure.AzureResourceManagerFinder; +import gyro.core.Type; /** * Query load balancer. @@ -36,7 +37,8 @@ * load-balancer: $(external-query azure::load-balancer {}) */ @Type("load-balancer") -public class LoadBalancerFinder extends AzureFinder { +public class LoadBalancerFinder extends AzureResourceManagerFinder { + private String id; /** @@ -51,12 +53,12 @@ public void setId(String id) { } @Override - protected List findAllAzure(Azure client) { - return client.loadBalancers().list(); + protected List findAllAzure(AzureResourceManager client) { + return client.loadBalancers().list().stream().collect(Collectors.toList()); } @Override - protected List findAzure(Azure client, Map filters) { + protected List findAzure(AzureResourceManager client, Map filters) { LoadBalancer loadBalancer = client.loadBalancers().getById(filters.get("id")); if (loadBalancer == null) { return Collections.emptyList(); diff --git a/src/main/java/gyro/azure/network/LoadBalancerResource.java b/src/main/java/gyro/azure/network/LoadBalancerResource.java index 6e72e58d..a1111bff 100644 --- a/src/main/java/gyro/azure/network/LoadBalancerResource.java +++ b/src/main/java/gyro/azure/network/LoadBalancerResource.java @@ -16,42 +16,42 @@ package gyro.azure.network; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import com.azure.core.management.Region; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.network.models.LoadBalancer; +import com.azure.resourcemanager.network.models.LoadBalancer.DefinitionStages.WithCreate; +import com.azure.resourcemanager.network.models.LoadBalancerHttpProbe; +import com.azure.resourcemanager.network.models.LoadBalancerPrivateFrontend; +import com.azure.resourcemanager.network.models.LoadBalancerPublicFrontend; +import com.azure.resourcemanager.network.models.LoadBalancerSkuType; +import com.azure.resourcemanager.network.models.LoadBalancerTcpProbe; +import com.azure.resourcemanager.network.models.LoadBalancingRule; +import com.azure.resourcemanager.network.models.Network; +import com.azure.resourcemanager.network.models.PublicIpAddress; +import com.azure.resourcemanager.network.models.TransportProtocol; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.azure.resources.ResourceGroupResource; import gyro.core.GyroUI; -import gyro.core.resource.Id; -import gyro.core.resource.Updatable; import gyro.core.Type; +import gyro.core.resource.Id; import gyro.core.resource.Output; import gyro.core.resource.Resource; - -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.network.LoadBalancer; -import com.microsoft.azure.management.network.LoadBalancerHttpProbe; -import com.microsoft.azure.management.network.LoadBalancerInboundNatPool; -import com.microsoft.azure.management.network.LoadBalancerPrivateFrontend; -import com.microsoft.azure.management.network.LoadBalancerPublicFrontend; -import com.microsoft.azure.management.network.LoadBalancingRule; -import com.microsoft.azure.management.network.LoadBalancerSkuType; -import com.microsoft.azure.management.network.LoadBalancerTcpProbe; -import com.microsoft.azure.management.network.Network; -import com.microsoft.azure.management.network.PublicIPAddress; -import com.microsoft.azure.management.network.TransportProtocol; -import com.microsoft.azure.management.network.LoadBalancer.DefinitionStages.WithCreate; -import com.microsoft.azure.management.resources.fluentcore.arm.Region; +import gyro.core.resource.Updatable; import gyro.core.scope.State; import gyro.core.validation.Required; import gyro.core.validation.ValidStrings; import gyro.core.validation.ValidationError; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; +import static com.azure.resourcemanager.network.models.LoadBalancerInboundNatPool.UpdateDefinitionStages.*; /** * Creates a load balancer. @@ -111,8 +111,6 @@ public class LoadBalancerResource extends AzureResource implements Copyable inboundNatPool; private Set inboundNatRule; - public enum SKU_TYPE { STANDARD, BASIC } - /** * The Health Check Http Probes associated with the Load Balancer. * @@ -244,7 +242,7 @@ public void setResourceGroup(ResourceGroupResource resourceGroup) { /** * Specifies the sku type for the Load Balancer. Defaults to ``BASIC``. */ - @ValidStrings({"BASIC", "STANDARD"}) + @ValidStrings({ "BASIC", "STANDARD" }) public SKU_TYPE getSkuType() { if (skuType == null) { skuType = SKU_TYPE.BASIC; @@ -351,7 +349,8 @@ public void copyFrom(LoadBalancer loadBalancer) { //private getAllFrontend getPrivateFrontend().clear(); - for (Map.Entry privateFrontend : loadBalancer.privateFrontends().entrySet()) { + for (Map.Entry privateFrontend : loadBalancer.privateFrontends() + .entrySet()) { PrivateFrontend frontendPrivate = newSubresource(PrivateFrontend.class); frontendPrivate.copyFrom(privateFrontend.getValue()); getPrivateFrontend().add(frontendPrivate); @@ -371,7 +370,7 @@ public void copyFrom(LoadBalancer loadBalancer) { //load balancing rules getLoadBalancerRule().clear(); - for (Map.Entry rule : loadBalancer.loadBalancingRules().entrySet()) { + for (Map.Entry rule : loadBalancer.loadBalancingRules().entrySet()) { LoadBalancerRule loadBalancerRule = newSubresource(LoadBalancerRule.class); loadBalancerRule.copyFrom(rule.getValue()); getLoadBalancerRule().add(loadBalancerRule); @@ -387,7 +386,7 @@ public void copyFrom(LoadBalancer loadBalancer) { @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); LoadBalancer loadBalancer = client.loadBalancers().getById(getId()); @@ -402,7 +401,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); LoadBalancer.DefinitionStages.WithLBRuleOrNat lb = client.loadBalancers() .define(getName()) @@ -413,7 +412,7 @@ public void create(GyroUI ui, State state) { // define the nat pools and rules if (!getInboundNatPool().isEmpty()) { - for (InboundNatPool natPool: getInboundNatPool()) { + for (InboundNatPool natPool : getInboundNatPool()) { buildLoadBalancer = lb.defineInboundNatPool(natPool.getName()) .withProtocol(TransportProtocol.fromString(natPool.getProtocol())) @@ -474,10 +473,10 @@ public void create(GyroUI ui, State state) { // define the public getAllFrontend for (PublicFrontend publicFrontend : getPublicFrontend()) { - PublicIPAddress ip = client.publicIPAddresses().getById(publicFrontend.getPublicIpAddress().getId()); + PublicIpAddress ip = client.publicIpAddresses().getById(publicFrontend.getPublicIpAddress().getId()); buildLoadBalancer.definePublicFrontend(publicFrontend.getName()) - .withExistingPublicIPAddress(ip) + .withExistingPublicIpAddress(ip) .attach(); } @@ -491,9 +490,9 @@ public void create(GyroUI ui, State state) { .withExistingSubnet(network, privateFrontend.getSubnetName()); if (privateFrontend.getPrivateIpAddress() != null) { - withAttachPrivate.withPrivateIPAddressStatic(privateFrontend.getPrivateIpAddress()); + withAttachPrivate.withPrivateIpAddressStatic(privateFrontend.getPrivateIpAddress()); } else { - withAttachPrivate.withPrivateIPAddressDynamic(); + withAttachPrivate.withPrivateIpAddressDynamic(); } withAttachPrivate.attach(); } @@ -507,7 +506,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); LoadBalancer loadBalancer = client.loadBalancers().getById(getId()); @@ -515,7 +514,6 @@ public void update(GyroUI ui, State state, Resource current, Set changed LoadBalancer.Update updateLoadBalancer = loadBalancer.update(); - // Update health check probe Http if (changedFieldNames.contains("health-check-probe-http")) { for (HealthCheckProbeHttp httpProbe : currentResource.getHealthCheckProbeHttp()) { @@ -564,9 +562,9 @@ public void update(GyroUI ui, State state, Resource current, Set changed .withExistingSubnet(network, privateFrontend.getSubnetName()); if (privateFrontend.getPrivateIpAddress() != null) { - withAttachPrivate.withPrivateIPAddressStatic(privateFrontend.getPrivateIpAddress()); + withAttachPrivate.withPrivateIpAddressStatic(privateFrontend.getPrivateIpAddress()); } else { - withAttachPrivate.withPrivateIPAddressDynamic(); + withAttachPrivate.withPrivateIpAddressDynamic(); } withAttachPrivate.attach(); @@ -580,11 +578,11 @@ public void update(GyroUI ui, State state, Resource current, Set changed } for (PublicFrontend publicFrontend : getPublicFrontend()) { - PublicIPAddress ip = client.publicIPAddresses().getById(publicFrontend.getPublicIpAddress().getId()); + PublicIpAddress ip = client.publicIpAddresses().getById(publicFrontend.getPublicIpAddress().getId()); updateLoadBalancer = updateLoadBalancer .definePublicFrontend(publicFrontend.getName()) - .withExistingPublicIPAddress(ip) + .withExistingPublicIpAddress(ip) .attach(); } } @@ -635,30 +633,32 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); client.loadBalancers().deleteByResourceGroup(getResourceGroup().getName(), getName()); } private void addNatPools(Set pools, LoadBalancer.Update updateLoadBalancer) { - LoadBalancerInboundNatPool.UpdateDefinitionStages.WithProtocol withName; - LoadBalancerInboundNatPool.UpdateDefinitionStages.WithFrontend withProtocol; - LoadBalancerInboundNatPool.UpdateDefinitionStages.WithFrontendPortRange withFrontend; - LoadBalancerInboundNatPool.UpdateDefinitionStages.WithBackendPort withPortRange; - LoadBalancerInboundNatPool.UpdateDefinitionStages.WithAttach withBackendPort; + WithProtocol withName; + WithFrontend withProtocol; + WithFrontendPortRange withFrontend; + WithBackendPort withPortRange; + WithAttach withBackendPort; for (InboundNatPool pool : pools) { withName = updateLoadBalancer.defineInboundNatPool(pool.getName()); withProtocol = - (LoadBalancerInboundNatPool.UpdateDefinitionStages.WithFrontend) withName.withProtocol(TransportProtocol.fromString(pool.getProtocol())); + (WithFrontend) withName.withProtocol(TransportProtocol.fromString(pool.getProtocol())); - withFrontend = (LoadBalancerInboundNatPool.UpdateDefinitionStages.WithFrontendPortRange) withProtocol.fromFrontend(pool.getFrontendName()); + withFrontend = (WithFrontendPortRange) withProtocol.fromFrontend(pool.getFrontendName()); - withPortRange = (LoadBalancerInboundNatPool.UpdateDefinitionStages.WithBackendPort) withFrontend.fromFrontendPortRange(pool.getFrontendPortStart(), pool.getFrontendPortEnd()); + withPortRange = (WithBackendPort) withFrontend.fromFrontendPortRange( + pool.getFrontendPortStart(), + pool.getFrontendPortEnd()); - withBackendPort = (LoadBalancerInboundNatPool.UpdateDefinitionStages.WithAttach) withPortRange.toBackendPort(pool.getBackendPort()); + withBackendPort = (WithAttach) withPortRange.toBackendPort(pool.getBackendPort()); withBackendPort.attach(); } @@ -682,9 +682,17 @@ public List validate() { List errors = new ArrayList<>(); if (!getInboundNatRule().isEmpty() && !getInboundNatPool().isEmpty()) { - errors.add(new ValidationError(this, "inbound-nat-rule", "'inbound-nat-rule' cannot be set when 'inbound-nat-pool' is set.")); + errors.add(new ValidationError( + this, + "inbound-nat-rule", + "'inbound-nat-rule' cannot be set when 'inbound-nat-pool' is set.")); } return errors; } + + public enum SKU_TYPE { + STANDARD, + BASIC + } } diff --git a/src/main/java/gyro/azure/network/LoadBalancerRule.java b/src/main/java/gyro/azure/network/LoadBalancerRule.java index 420a9420..4c235ded 100644 --- a/src/main/java/gyro/azure/network/LoadBalancerRule.java +++ b/src/main/java/gyro/azure/network/LoadBalancerRule.java @@ -16,12 +16,11 @@ package gyro.azure.network; +import com.azure.resourcemanager.network.models.LoadBalancingRule; +import com.azure.resourcemanager.network.models.TransportProtocol; import gyro.azure.Copyable; import gyro.core.resource.Diffable; import gyro.core.resource.Updatable; - -import com.microsoft.azure.management.network.LoadBalancingRule; -import com.microsoft.azure.management.network.TransportProtocol; import gyro.core.validation.Required; /** @@ -45,6 +44,7 @@ * end */ public class LoadBalancerRule extends Diffable implements Copyable { + private String backendName; private Integer backendPort; private Boolean floatingIp; diff --git a/src/main/java/gyro/azure/network/NetworkFinder.java b/src/main/java/gyro/azure/network/NetworkFinder.java index 24ab205a..c3be4fd0 100644 --- a/src/main/java/gyro/azure/network/NetworkFinder.java +++ b/src/main/java/gyro/azure/network/NetworkFinder.java @@ -16,18 +16,19 @@ package gyro.azure.network; -import com.azure.resourcemanager.AzureResourceManager; -import com.azure.resourcemanager.network.models.Network; -import gyro.azure.AzureResourceManagerFinder; -import gyro.core.Type; - import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.network.models.Network; +import gyro.azure.AzureResourceManagerFinder; +import gyro.core.Type; + @Type("network") public class NetworkFinder extends AzureResourceManagerFinder { + private String id; /** diff --git a/src/main/java/gyro/azure/network/NetworkInterfaceFinder.java b/src/main/java/gyro/azure/network/NetworkInterfaceFinder.java index 011f6e3b..f290dbb2 100644 --- a/src/main/java/gyro/azure/network/NetworkInterfaceFinder.java +++ b/src/main/java/gyro/azure/network/NetworkInterfaceFinder.java @@ -16,14 +16,15 @@ package gyro.azure.network; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.network.NetworkInterface; -import gyro.azure.AzureFinder; -import gyro.core.Type; - import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; + +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.network.models.NetworkInterface; +import gyro.azure.AzureResourceManagerFinder; +import gyro.core.Type; /** * Query network interface. @@ -36,7 +37,8 @@ * network-interface: $(external-query azure::network-interface {}) */ @Type("network-interface") -public class NetworkInterfaceFinder extends AzureFinder { +public class NetworkInterfaceFinder extends AzureResourceManagerFinder { + private String id; /** @@ -51,12 +53,12 @@ public void setId(String id) { } @Override - protected List findAllAzure(Azure client) { - return client.networkInterfaces().list(); + protected List findAllAzure(AzureResourceManager client) { + return client.networkInterfaces().list().stream().collect(Collectors.toList()); } @Override - protected List findAzure(Azure client, Map filters) { + protected List findAzure(AzureResourceManager client, Map filters) { NetworkInterface networkInterface = client.networkInterfaces().getById(filters.get("id")); if (networkInterface == null) { return Collections.emptyList(); diff --git a/src/main/java/gyro/azure/network/NetworkInterfaceResource.java b/src/main/java/gyro/azure/network/NetworkInterfaceResource.java index 1613af34..51958d47 100644 --- a/src/main/java/gyro/azure/network/NetworkInterfaceResource.java +++ b/src/main/java/gyro/azure/network/NetworkInterfaceResource.java @@ -16,32 +16,31 @@ package gyro.azure.network; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.network.NetworkInterface; -import com.microsoft.azure.management.network.NicIPConfiguration; -import com.microsoft.azure.management.resources.fluentcore.arm.Region; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.azure.core.management.Region; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.network.models.NetworkInterface; +import com.azure.resourcemanager.network.models.NicIpConfiguration; import com.psddev.dari.util.ObjectUtils; import gyro.azure.AzureResource; - import gyro.azure.Copyable; import gyro.azure.resources.ResourceGroupResource; import gyro.core.GyroUI; -import gyro.core.resource.Id; -import gyro.core.resource.Updatable; import gyro.core.Type; +import gyro.core.resource.Id; import gyro.core.resource.Output; import gyro.core.resource.Resource; +import gyro.core.resource.Updatable; import gyro.core.scope.State; import gyro.core.validation.Required; import gyro.core.validation.ValidationError; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - /** * Creates a network interface. * @@ -73,6 +72,7 @@ */ @Type("network-interface") public class NetworkInterfaceResource extends AzureResource implements Copyable { + private String name; private ResourceGroupResource resourceGroup; private NetworkResource network; @@ -206,12 +206,14 @@ public void copyFrom(NetworkInterface networkInterface) { setId(networkInterface.id()); setName(networkInterface.name()); setResourceGroup(findById(ResourceGroupResource.class, networkInterface.resourceGroupName())); - setSecurityGroup(networkInterface.getNetworkSecurityGroup() != null ? findById(NetworkSecurityGroupResource.class, networkInterface.getNetworkSecurityGroup().id()) : null); + setSecurityGroup(networkInterface.getNetworkSecurityGroup() != null ? findById( + NetworkSecurityGroupResource.class, + networkInterface.getNetworkSecurityGroup().id()) : null); setTags(networkInterface.tags()); setIpForwarding(networkInterface.isIPForwardingEnabled()); getNicIpConfiguration().clear(); - for (NicIPConfiguration nicIpConfiguration : networkInterface.ipConfigurations().values()) { + for (NicIpConfiguration nicIpConfiguration : networkInterface.ipConfigurations().values()) { NicIpConfigurationResource nicIpConfigurationResource = newSubresource(NicIpConfigurationResource.class); nicIpConfigurationResource.copyFrom(nicIpConfiguration); @@ -221,7 +223,7 @@ public void copyFrom(NetworkInterface networkInterface) { @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); NetworkInterface networkInterface = getNetworkInterface(client); @@ -236,7 +238,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); NetworkInterface.DefinitionStages.WithPrimaryPrivateIP withPrimaryPrivateIP = client.networkInterfaces() .define(getName()) @@ -247,7 +249,10 @@ public void create(GyroUI ui, State state) { NetworkInterface.DefinitionStages.WithCreate withCreate; - NicIpConfigurationResource primary = getNicIpConfiguration().stream().filter(NicIpConfigurationResource::isPrimary).findFirst().get(); + NicIpConfigurationResource primary = getNicIpConfiguration().stream() + .filter(NicIpConfigurationResource::isPrimary) + .findFirst() + .get(); if (!ObjectUtils.isBlank(primary.getPrivateIpAddress())) { withCreate = withPrimaryPrivateIP.withPrimaryPrivateIPAddressStatic(primary.getPrivateIpAddress()); @@ -256,15 +261,18 @@ public void create(GyroUI ui, State state) { } if (getSecurityGroup() != null) { - withCreate = withCreate.withExistingNetworkSecurityGroup(client.networkSecurityGroups().getById(getSecurityGroup().getId())); + withCreate = withCreate.withExistingNetworkSecurityGroup(client.networkSecurityGroups() + .getById(getSecurityGroup().getId())); } for (NicBackend backend : primary.getNicBackend()) { - withCreate.withExistingLoadBalancerBackend(client.loadBalancers().getById(backend.getLoadBalancer().getId()), backend.getBackendName()); + withCreate.withExistingLoadBalancerBackend(client.loadBalancers() + .getById(backend.getLoadBalancer().getId()), backend.getBackendName()); } for (NicNatRule rule : primary.getNicNatRule()) { - withCreate.withExistingLoadBalancerInboundNatRule(client.loadBalancers().getById(rule.getLoadBalancer().getId()), rule.getInboundNatRuleName()); + withCreate.withExistingLoadBalancerInboundNatRule(client.loadBalancers() + .getById(rule.getLoadBalancer().getId()), rule.getInboundNatRuleName()); } if (getIpForwarding()) { @@ -278,7 +286,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); NetworkInterface networkInterface = getNetworkInterface(client); @@ -288,7 +296,8 @@ public void update(GyroUI ui, State state, Resource current, Set changed if (getSecurityGroup() == null) { update = update.withoutNetworkSecurityGroup(); } else { - update = update.withExistingNetworkSecurityGroup(client.networkSecurityGroups().getById(getSecurityGroup().getId())); + update = update.withExistingNetworkSecurityGroup(client.networkSecurityGroups() + .getById(getSecurityGroup().getId())); } } @@ -307,12 +316,12 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); client.networkInterfaces().deleteByResourceGroup(getResourceGroup().getName(), getName()); } - NetworkInterface getNetworkInterface(Azure client) { + NetworkInterface getNetworkInterface(AzureResourceManager client) { return client.networkInterfaces().getById(getId()); } @@ -321,7 +330,10 @@ public List validate() { List errors = new ArrayList<>(); if (getNicIpConfiguration().stream().filter(NicIpConfigurationResource::isPrimary).count() != 1) { - errors.add(new ValidationError(this, "nic-ip-configuration", "One and only one Ip configuration named as primary is required.")); + errors.add(new ValidationError( + this, + "nic-ip-configuration", + "One and only one Ip configuration named as primary is required.")); } return errors; diff --git a/src/main/java/gyro/azure/network/NetworkResource.java b/src/main/java/gyro/azure/network/NetworkResource.java index 47dab934..f65818d7 100644 --- a/src/main/java/gyro/azure/network/NetworkResource.java +++ b/src/main/java/gyro/azure/network/NetworkResource.java @@ -16,6 +16,13 @@ package gyro.azure.network; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Predicate; +import java.util.stream.Collectors; import com.azure.core.management.Region; import com.azure.resourcemanager.AzureResourceManager; @@ -25,22 +32,14 @@ import gyro.azure.Copyable; import gyro.azure.resources.ResourceGroupResource; import gyro.core.GyroUI; -import gyro.core.resource.Id; -import gyro.core.resource.Updatable; import gyro.core.Type; +import gyro.core.resource.Id; import gyro.core.resource.Output; import gyro.core.resource.Resource; +import gyro.core.resource.Updatable; import gyro.core.scope.State; import gyro.core.validation.Required; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Predicate; -import java.util.stream.Collectors; - /** * Creates a virtual network. * @@ -74,6 +73,7 @@ */ @Type("network") public class NetworkResource extends AzureResource implements Copyable { + private String name; private ResourceGroupResource resourceGroup; private Set addressSpaces; diff --git a/src/main/java/gyro/azure/network/NetworkSecurityGroupFinder.java b/src/main/java/gyro/azure/network/NetworkSecurityGroupFinder.java index abc0c19e..d184aa1e 100644 --- a/src/main/java/gyro/azure/network/NetworkSecurityGroupFinder.java +++ b/src/main/java/gyro/azure/network/NetworkSecurityGroupFinder.java @@ -16,14 +16,15 @@ package gyro.azure.network; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.network.NetworkSecurityGroup; -import gyro.azure.AzureFinder; -import gyro.core.Type; - import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; + +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.network.models.NetworkSecurityGroup; +import gyro.azure.AzureResourceManagerFinder; +import gyro.core.Type; /** * Query network security group. @@ -36,7 +37,9 @@ * network-security-group: $(external-query azure::network-security-group {}) */ @Type("network-security-group") -public class NetworkSecurityGroupFinder extends AzureFinder { +public class NetworkSecurityGroupFinder + extends AzureResourceManagerFinder { + private String id; /** @@ -49,13 +52,14 @@ public String getId() { public void setId(String id) { this.id = id; } + @Override - protected List findAllAzure(Azure client) { - return client.networkSecurityGroups().list(); + protected List findAllAzure(AzureResourceManager client) { + return client.networkSecurityGroups().list().stream().collect(Collectors.toList()); } @Override - protected List findAzure(Azure client, Map filters) { + protected List findAzure(AzureResourceManager client, Map filters) { NetworkSecurityGroup networkSecurityGroup = client.networkSecurityGroups().getById(filters.get("id")); if (networkSecurityGroup == null) { return Collections.emptyList(); diff --git a/src/main/java/gyro/azure/network/NetworkSecurityGroupResource.java b/src/main/java/gyro/azure/network/NetworkSecurityGroupResource.java index 73a5a418..0ee6f1b0 100644 --- a/src/main/java/gyro/azure/network/NetworkSecurityGroupResource.java +++ b/src/main/java/gyro/azure/network/NetworkSecurityGroupResource.java @@ -16,26 +16,26 @@ package gyro.azure.network; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.network.NetworkSecurityGroup; -import com.microsoft.azure.management.resources.fluentcore.arm.Region; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import com.azure.core.management.Region; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.network.models.NetworkSecurityGroup; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.azure.resources.ResourceGroupResource; import gyro.core.GyroUI; -import gyro.core.resource.Id; -import gyro.core.resource.Updatable; import gyro.core.Type; +import gyro.core.resource.Id; import gyro.core.resource.Output; import gyro.core.resource.Resource; +import gyro.core.resource.Updatable; import gyro.core.scope.State; import gyro.core.validation.Required; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - /** * Creates a network security group. * @@ -76,6 +76,7 @@ */ @Type("network-security-group") public class NetworkSecurityGroupResource extends AzureResource implements Copyable { + private String name; private ResourceGroupResource resourceGroup; private String id; @@ -170,7 +171,7 @@ public void copyFrom(NetworkSecurityGroup networkSecurityGroup) { @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); NetworkSecurityGroup networkSecurityGroup = client.networkSecurityGroups().getById(getId()); @@ -185,7 +186,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); NetworkSecurityGroup networkSecurityGroup = client.networkSecurityGroups() .define(getName()) @@ -199,7 +200,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); NetworkSecurityGroup networkSecurityGroup = client.networkSecurityGroups().getById(getId()); @@ -208,7 +209,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); client.networkSecurityGroups().deleteById(getId()); } diff --git a/src/main/java/gyro/azure/network/NetworkSecurityGroupRuleResource.java b/src/main/java/gyro/azure/network/NetworkSecurityGroupRuleResource.java index 946c5b2a..8b128a03 100644 --- a/src/main/java/gyro/azure/network/NetworkSecurityGroupRuleResource.java +++ b/src/main/java/gyro/azure/network/NetworkSecurityGroupRuleResource.java @@ -16,29 +16,34 @@ package gyro.azure.network; +import java.util.Collections; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.network.models.NetworkSecurityGroup; +import com.azure.resourcemanager.network.models.NetworkSecurityRule; +import com.azure.resourcemanager.network.models.SecurityRuleAccess; +import com.azure.resourcemanager.network.models.SecurityRuleDirection; +import com.azure.resourcemanager.network.models.SecurityRuleProtocol; import com.google.common.collect.ImmutableMap; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.network.NetworkSecurityGroup; -import com.microsoft.azure.management.network.NetworkSecurityRule; -import com.microsoft.azure.management.network.SecurityRuleAccess; -import com.microsoft.azure.management.network.SecurityRuleDirection; -import com.microsoft.azure.management.network.SecurityRuleProtocol; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.core.GyroUI; -import gyro.core.resource.Updatable; import gyro.core.resource.Resource; +import gyro.core.resource.Updatable; import gyro.core.scope.State; import gyro.core.validation.Range; import gyro.core.validation.Required; import gyro.core.validation.ValidStrings; -import java.util.Collections; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - public class NetworkSecurityGroupRuleResource extends AzureResource implements Copyable { + + private static final Map protocolMap = ImmutableMap + .of("all", SecurityRuleProtocol.ASTERISK, + "tcp", SecurityRuleProtocol.TCP, + "udp", SecurityRuleProtocol.UDP); private String name; private Boolean inboundRule; private Boolean allowRule; @@ -52,11 +57,6 @@ public class NetworkSecurityGroupRuleResource extends AzureResource implements C private Integer priority; private String protocol; - private static final Map protocolMap = ImmutableMap - .of("all", SecurityRuleProtocol.ASTERISK, - "tcp", SecurityRuleProtocol.TCP, - "udp", SecurityRuleProtocol.UDP); - /** * Name of the Network Security Rule. */ @@ -220,7 +220,7 @@ public void setPriority(Integer priority) { /** * Protocol for the Network Security Rule. Defaults to ``all``. */ - @ValidStrings({"all", "tcp", "udp"}) + @ValidStrings({ "all", "tcp", "udp" }) @Updatable public String getProtocol() { if (protocol == null) { @@ -266,14 +266,20 @@ public void copyFrom(NetworkSecurityRule networkSecurityRule) { setDescription(networkSecurityRule.description()); setPriority(networkSecurityRule.priority()); - setProtocol(networkSecurityRule.protocol().toString().equals("*") ? "all" : networkSecurityRule.protocol().toString()); + setProtocol(networkSecurityRule.protocol().toString().equals("*") + ? "all" + : networkSecurityRule.protocol().toString()); if (!networkSecurityRule.sourceApplicationSecurityGroupIds().isEmpty()) { - setFromApplicationSecurityGroup(findById(ApplicationSecurityGroupResource.class, networkSecurityRule.sourceApplicationSecurityGroupIds().iterator().next())); + setFromApplicationSecurityGroup(findById( + ApplicationSecurityGroupResource.class, + networkSecurityRule.sourceApplicationSecurityGroupIds().iterator().next())); } if (!networkSecurityRule.destinationApplicationSecurityGroupIds().isEmpty()) { - setToApplicationSecurityGroup(findById(ApplicationSecurityGroupResource.class, networkSecurityRule.destinationApplicationSecurityGroupIds().iterator().next())); + setToApplicationSecurityGroup(findById( + ApplicationSecurityGroupResource.class, + networkSecurityRule.destinationApplicationSecurityGroupIds().iterator().next())); } } @@ -284,7 +290,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); NetworkSecurityGroupResource parent = (NetworkSecurityGroupResource) parent(); @@ -350,7 +356,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); NetworkSecurityGroupResource parent = (NetworkSecurityGroupResource) parent(); @@ -405,7 +411,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); NetworkSecurityGroupResource parent = (NetworkSecurityGroupResource) parent(); diff --git a/src/main/java/gyro/azure/network/NicBackend.java b/src/main/java/gyro/azure/network/NicBackend.java index 7fccf5b1..e3ba2723 100644 --- a/src/main/java/gyro/azure/network/NicBackend.java +++ b/src/main/java/gyro/azure/network/NicBackend.java @@ -16,10 +16,9 @@ package gyro.azure.network; +import com.azure.resourcemanager.network.models.LoadBalancerBackend; import gyro.azure.Copyable; import gyro.core.resource.Diffable; - -import com.microsoft.azure.management.network.LoadBalancerBackend; import gyro.core.validation.Required; /** diff --git a/src/main/java/gyro/azure/network/NicIpConfigurationResource.java b/src/main/java/gyro/azure/network/NicIpConfigurationResource.java index c0ffb602..8bb8253b 100644 --- a/src/main/java/gyro/azure/network/NicIpConfigurationResource.java +++ b/src/main/java/gyro/azure/network/NicIpConfigurationResource.java @@ -21,14 +21,14 @@ import java.util.Set; import java.util.stream.Collectors; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.network.LoadBalancer; -import com.microsoft.azure.management.network.LoadBalancerBackend; -import com.microsoft.azure.management.network.LoadBalancerInboundNatRule; -import com.microsoft.azure.management.network.NetworkInterface; -import com.microsoft.azure.management.network.NicIPConfiguration; -import com.microsoft.azure.management.network.implementation.ApplicationSecurityGroupInner; -import com.microsoft.azure.management.network.implementation.NetworkInterfaceIPConfigurationInner; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.network.fluent.models.ApplicationSecurityGroupInner; +import com.azure.resourcemanager.network.fluent.models.NetworkInterfaceIpConfigurationInner; +import com.azure.resourcemanager.network.models.LoadBalancer; +import com.azure.resourcemanager.network.models.LoadBalancerBackend; +import com.azure.resourcemanager.network.models.LoadBalancerInboundNatRule; +import com.azure.resourcemanager.network.models.NetworkInterface; +import com.azure.resourcemanager.network.models.NicIpConfiguration; import com.psddev.dari.util.ObjectUtils; import gyro.azure.AzureResource; import gyro.azure.Copyable; @@ -38,7 +38,7 @@ import gyro.core.scope.State; import gyro.core.validation.Required; -public class NicIpConfigurationResource extends AzureResource implements Copyable { +public class NicIpConfigurationResource extends AzureResource implements Copyable { private String name; private PublicIpAddressResource publicIpAddress; @@ -138,12 +138,12 @@ public void setApplicationSecurityGroups(Set a } @Override - public void copyFrom(NicIPConfiguration nicIpConfiguration) { + public void copyFrom(NicIpConfiguration nicIpConfiguration) { setName(nicIpConfiguration.name()); - setPublicIpAddress(nicIpConfiguration.getPublicIPAddress() != null ? findById( + setPublicIpAddress(nicIpConfiguration.getPublicIpAddress() != null ? findById( PublicIpAddressResource.class, - nicIpConfiguration.getPublicIPAddress().id()) : null); - setPrivateIpAddress(nicIpConfiguration.privateIPAddress()); + nicIpConfiguration.getPublicIpAddress().id()) : null); + setPrivateIpAddress(nicIpConfiguration.privateIpAddress()); getNicBackend().clear(); for (LoadBalancerBackend backend : nicIpConfiguration.listAssociatedLoadBalancerBackends()) { @@ -160,8 +160,8 @@ public void copyFrom(NicIPConfiguration nicIpConfiguration) { } getApplicationSecurityGroups().clear(); - if (nicIpConfiguration.inner().applicationSecurityGroups() != null) { - setApplicationSecurityGroups(nicIpConfiguration.inner() + if (nicIpConfiguration.innerModel().applicationSecurityGroups() != null) { + setApplicationSecurityGroups(nicIpConfiguration.innerModel() .applicationSecurityGroups() .stream() .map(o -> findById(ApplicationSecurityGroupResource.class, o.id())) @@ -185,28 +185,28 @@ public void create(GyroUI ui, State state) { return; } - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); NetworkInterfaceResource parent = (NetworkInterfaceResource) parent(); NetworkInterface networkInterface = parent.getNetworkInterface(client); - NicIPConfiguration.UpdateDefinitionStages.WithPrivateIP updateWithPrivateIP = networkInterface + NicIpConfiguration.UpdateDefinitionStages.WithPrivateIP updateWithPrivateIP = networkInterface .update() .defineSecondaryIPConfiguration(getName()) .withExistingNetwork(client.networks().getById(parent.getNetwork().getId())) .withSubnet(parent.getSubnet()); - NicIPConfiguration.UpdateDefinitionStages.WithAttach updateWithAttach; + NicIpConfiguration.UpdateDefinitionStages.WithAttach updateWithAttach; if (!ObjectUtils.isBlank(getPrivateIpAddress())) { - updateWithAttach = updateWithPrivateIP.withPrivateIPAddressStatic(getPrivateIpAddress()); + updateWithAttach = updateWithPrivateIP.withPrivateIpAddressStatic(getPrivateIpAddress()); } else { - updateWithAttach = updateWithPrivateIP.withPrivateIPAddressDynamic(); + updateWithAttach = updateWithPrivateIP.withPrivateIpAddressDynamic(); } if (getPublicIpAddress() != null) { - updateWithAttach = updateWithAttach.withExistingPublicIPAddress(client.publicIPAddresses() + updateWithAttach = updateWithAttach.withExistingPublicIpAddress(client.publicIpAddresses() .getById(getPublicIpAddress().getId())); } @@ -229,28 +229,28 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); NetworkInterfaceResource parent = (NetworkInterfaceResource) parent(); NetworkInterface networkInterface = parent.getNetworkInterface(client); - NicIPConfiguration.Update update = networkInterface.update().updateIPConfiguration(getName()) + NicIpConfiguration.Update update = networkInterface.update().updateIPConfiguration(getName()) .withSubnet(parent.getSubnet()); if (changedFieldNames.contains("public-ip-address")) { if (getPublicIpAddress() == null) { - update = update.withoutPublicIPAddress(); + update = update.withoutPublicIpAddress(); } else { - update = update.withExistingPublicIPAddress(client.publicIPAddresses() + update = update.withExistingPublicIpAddress(client.publicIpAddresses() .getById(getPublicIpAddress().getId())); } } if (!ObjectUtils.isBlank(getPrivateIpAddress())) { - update = update.withPrivateIPAddressStatic(getPrivateIpAddress()); + update = update.withPrivateIpAddressStatic(getPrivateIpAddress()); } else { - update = update.withPrivateIPAddressDynamic(); + update = update.withPrivateIpAddressDynamic(); } update.withoutLoadBalancerBackends(); @@ -270,8 +270,8 @@ public void update(GyroUI ui, State state, Resource current, Set changed addRemoveApplicationSecurityGroups(client, networkInterface); } - private void addRemoveApplicationSecurityGroups(Azure client, NetworkInterface networkInterface) { - NetworkInterfaceIPConfigurationInner nicIPConfigurationInner = networkInterface.inner() + private void addRemoveApplicationSecurityGroups(AzureResourceManager client, NetworkInterface networkInterface) { + NetworkInterfaceIpConfigurationInner nicIPConfigurationInner = networkInterface.innerModel() .ipConfigurations() .stream() .filter(o -> o.name().equals(getName())) @@ -293,12 +293,7 @@ private void addRemoveApplicationSecurityGroups(Azure client, NetworkInterface n } if (doUpdate) { - client.networkInterfaces() - .inner() - .createOrUpdate( - networkInterface.resourceGroupName(), - networkInterface.name(), - networkInterface.inner()); + networkInterface.update().apply(); } } @@ -308,7 +303,7 @@ public void delete(GyroUI ui, State state) { return; } - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); NetworkInterfaceResource parent = (NetworkInterfaceResource) parent(); diff --git a/src/main/java/gyro/azure/network/NicNatRule.java b/src/main/java/gyro/azure/network/NicNatRule.java index 15eec04a..ab1b6958 100644 --- a/src/main/java/gyro/azure/network/NicNatRule.java +++ b/src/main/java/gyro/azure/network/NicNatRule.java @@ -16,10 +16,9 @@ package gyro.azure.network; +import com.azure.resourcemanager.network.models.LoadBalancerInboundNatRule; import gyro.azure.Copyable; import gyro.core.resource.Diffable; - -import com.microsoft.azure.management.network.LoadBalancerInboundNatRule; import gyro.core.validation.Required; /** @@ -36,6 +35,7 @@ * end */ public class NicNatRule extends Diffable implements Copyable { + private LoadBalancerResource loadBalancer; private String inboundNatRuleName; diff --git a/src/main/java/gyro/azure/network/PrivateFrontend.java b/src/main/java/gyro/azure/network/PrivateFrontend.java index c5da30c5..d587ab6d 100644 --- a/src/main/java/gyro/azure/network/PrivateFrontend.java +++ b/src/main/java/gyro/azure/network/PrivateFrontend.java @@ -16,11 +16,10 @@ package gyro.azure.network; +import com.azure.resourcemanager.network.models.LoadBalancerPrivateFrontend; import gyro.azure.Copyable; import gyro.core.resource.Diffable; import gyro.core.resource.Updatable; - -import com.microsoft.azure.management.network.LoadBalancerPrivateFrontend; import gyro.core.validation.Required; /** @@ -38,6 +37,7 @@ * end */ public class PrivateFrontend extends Diffable implements Copyable { + private String name; private String privateIpAddress; private String subnetName; @@ -96,7 +96,7 @@ public void setSubnetName(String subnetName) { @Override public void copyFrom(LoadBalancerPrivateFrontend privateFrontend) { setName(privateFrontend.name()); - setPrivateIpAddress(privateFrontend.privateIPAddress()); + setPrivateIpAddress(privateFrontend.privateIpAddress()); setSubnetName(privateFrontend.subnetName()); setNetwork(findById(NetworkResource.class, privateFrontend.networkId())); } diff --git a/src/main/java/gyro/azure/network/Probe.java b/src/main/java/gyro/azure/network/Probe.java index 8b17f075..b9aabc5e 100644 --- a/src/main/java/gyro/azure/network/Probe.java +++ b/src/main/java/gyro/azure/network/Probe.java @@ -16,20 +16,20 @@ package gyro.azure.network; -import com.microsoft.azure.management.network.ApplicationGateway.Update; -import com.microsoft.azure.management.network.ApplicationGatewayProbe; -import com.microsoft.azure.management.network.ApplicationGatewayProbe.UpdateDefinitionStages.WithProtocol; -import com.microsoft.azure.management.network.ApplicationGatewayProbe.UpdateDefinitionStages.WithAttach; -import com.microsoft.azure.management.network.ApplicationGatewayProtocol; -import com.microsoft.azure.management.network.ApplicationGateway.DefinitionStages.WithCreate; +import java.util.HashSet; +import java.util.Set; + +import com.azure.resourcemanager.network.models.ApplicationGateway.DefinitionStages.WithCreate; +import com.azure.resourcemanager.network.models.ApplicationGateway.Update; +import com.azure.resourcemanager.network.models.ApplicationGatewayProbe; +import com.azure.resourcemanager.network.models.ApplicationGatewayProbe.UpdateDefinitionStages.WithAttach; +import com.azure.resourcemanager.network.models.ApplicationGatewayProbe.UpdateDefinitionStages.WithProtocol; +import com.azure.resourcemanager.network.models.ApplicationGatewayProtocol; import gyro.azure.Copyable; import gyro.core.resource.Diffable; import gyro.core.resource.Updatable; import gyro.core.validation.Required; -import java.util.HashSet; -import java.util.Set; - /** * Creates a Probe. * @@ -53,6 +53,7 @@ * end */ public class Probe extends Diffable implements Copyable { + private String name; private String hostName; private String path; @@ -203,7 +204,7 @@ public void copyFrom(ApplicationGatewayProbe probe) { setUnhealthyThreshold(probe.retriesBeforeUnhealthy()); setHttpResponseCodes(new HashSet<>(probe.healthyHttpResponseStatusCodeRanges())); setHttpResponseBodyMatch(probe.healthyHttpResponseBodyContents()); - setHttpsProtocol(probe.inner().protocol().equals(ApplicationGatewayProtocol.HTTPS)); + setHttpsProtocol(probe.innerModel().protocol().equals(ApplicationGatewayProtocol.HTTPS)); } @Override @@ -212,7 +213,8 @@ public String primaryKey() { } WithCreate createProbe(WithCreate attach) { - ApplicationGatewayProbe.DefinitionStages.WithProtocol attachWithProtocol = attach.defineProbe(getName()) + ApplicationGatewayProbe.DefinitionStages.WithProtocol attachWithProtocol = attach.defineProbe( + getName()) .withHost(getHostName()).withPath(getPath()); ApplicationGatewayProbe.DefinitionStages.WithAttach withCreateWithAttach; diff --git a/src/main/java/gyro/azure/network/PublicFrontend.java b/src/main/java/gyro/azure/network/PublicFrontend.java index a6f4a8af..47e61288 100644 --- a/src/main/java/gyro/azure/network/PublicFrontend.java +++ b/src/main/java/gyro/azure/network/PublicFrontend.java @@ -16,11 +16,10 @@ package gyro.azure.network; +import com.azure.resourcemanager.network.models.LoadBalancerPublicFrontend; import gyro.azure.Copyable; import gyro.core.resource.Diffable; import gyro.core.resource.Updatable; - -import com.microsoft.azure.management.network.LoadBalancerPublicFrontend; import gyro.core.validation.Required; /** @@ -69,7 +68,7 @@ public void setPublicIpAddress(PublicIpAddressResource publicIpAddressName) { @Override public void copyFrom(LoadBalancerPublicFrontend publicFrontend) { setName(publicFrontend.name()); - setPublicIpAddress(findById(PublicIpAddressResource.class, publicFrontend.getPublicIPAddress().id())); + setPublicIpAddress(findById(PublicIpAddressResource.class, publicFrontend.getPublicIpAddress().id())); } public String primaryKey() { diff --git a/src/main/java/gyro/azure/network/PublicIpAddressFinder.java b/src/main/java/gyro/azure/network/PublicIpAddressFinder.java index 596adbf6..d1ab9d84 100644 --- a/src/main/java/gyro/azure/network/PublicIpAddressFinder.java +++ b/src/main/java/gyro/azure/network/PublicIpAddressFinder.java @@ -16,16 +16,16 @@ package gyro.azure.network; -import com.azure.resourcemanager.AzureResourceManager; -import com.azure.resourcemanager.network.models.PublicIpAddress; -import gyro.azure.AzureResourceManagerFinder; -import gyro.core.Type; - import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.network.models.PublicIpAddress; +import gyro.azure.AzureResourceManagerFinder; +import gyro.core.Type; + /** * Query public ip address. * @@ -38,6 +38,7 @@ */ @Type("public-ip-address") public class PublicIpAddressFinder extends AzureResourceManagerFinder { + private String id; /** diff --git a/src/main/java/gyro/azure/network/PublicIpAddressResource.java b/src/main/java/gyro/azure/network/PublicIpAddressResource.java index 946469c8..9741e500 100644 --- a/src/main/java/gyro/azure/network/PublicIpAddressResource.java +++ b/src/main/java/gyro/azure/network/PublicIpAddressResource.java @@ -16,6 +16,11 @@ package gyro.azure.network; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; import com.azure.core.management.Region; import com.azure.core.util.ExpandableStringEnum; @@ -30,22 +35,16 @@ import gyro.azure.Copyable; import gyro.azure.resources.ResourceGroupResource; import gyro.core.GyroUI; -import gyro.core.resource.Id; -import gyro.core.resource.Updatable; import gyro.core.Type; +import gyro.core.resource.Id; import gyro.core.resource.Output; import gyro.core.resource.Resource; +import gyro.core.resource.Updatable; import gyro.core.scope.State; import gyro.core.validation.Range; import gyro.core.validation.Required; import gyro.core.validation.ValidStrings; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - /** * Creates a public ip address. * @@ -66,6 +65,7 @@ */ @Type("public-ip-address") public class PublicIpAddressResource extends AzureResource implements Copyable { + private String name; private ResourceGroupResource resourceGroup; private SKU_TYPE skuType; @@ -83,8 +83,6 @@ public class PublicIpAddressResource extends AzureResource implements Copyable

{ + private String name; private String type; private String targetListener; @@ -66,9 +67,9 @@ public void setName(String name) { } /** - * Type of the redirect configuration. Valid values are ``Permanent`` or ``Found`` or ``SeeOther`` or ``Temporary`` + * Type of the redirect configuration. Valid values are ``Permanent`` or ``Found`` or ``SeeOther`` or ``Temporary`` */ - @ValidStrings({"Permanent", "Found", "SeeOther", "Temporary"}) + @ValidStrings({ "Permanent", "Found", "SeeOther", "Temporary" }) @Required @Updatable public String getType() { @@ -145,7 +146,8 @@ public void setIncludePath(Boolean includePath) { public void copyFrom(ApplicationGatewayRedirectConfiguration redirectConfiguration) { setName(redirectConfiguration.name()); setType(redirectConfiguration.type().toString()); - setTargetListener(redirectConfiguration.targetListener() != null ? redirectConfiguration.targetListener().name() : null); + setTargetListener( + redirectConfiguration.targetListener() != null ? redirectConfiguration.targetListener().name() : null); setTargetUrl(redirectConfiguration.targetUrl()); setIncludePath(redirectConfiguration.isPathIncluded()); setIncludeQueryString(redirectConfiguration.isQueryStringIncluded()); diff --git a/src/main/java/gyro/azure/network/RemoveApplicationGatewayCertificateCommand.java b/src/main/java/gyro/azure/network/RemoveApplicationGatewayCertificateCommand.java index 8e88f791..a6b37f0f 100644 --- a/src/main/java/gyro/azure/network/RemoveApplicationGatewayCertificateCommand.java +++ b/src/main/java/gyro/azure/network/RemoveApplicationGatewayCertificateCommand.java @@ -2,8 +2,8 @@ import java.util.List; -import com.microsoft.azure.management.network.ApplicationGateway; -import com.microsoft.azure.management.network.ApplicationGatewayListener; +import com.azure.resourcemanager.network.models.ApplicationGateway; +import com.azure.resourcemanager.network.models.ApplicationGatewayListener; import gyro.core.GyroCore; import gyro.core.GyroException; import picocli.CommandLine.Command; @@ -26,7 +26,7 @@ public void execute() throws Exception { String applicationGatewayResourceName = arguments.get(0); String certificateName = arguments.get(1); - ApplicationGateway applicationGateway = getApplicationGateway(applicationGatewayResourceName); + ApplicationGateway applicationGateway = getApplicationGatewayResourceManager(applicationGatewayResourceName); ApplicationGatewayListener listener = applicationGateway.listeners() .values() diff --git a/src/main/java/gyro/azure/network/RequestRoutingRule.java b/src/main/java/gyro/azure/network/RequestRoutingRule.java index 182d4cc8..a82d5c88 100644 --- a/src/main/java/gyro/azure/network/RequestRoutingRule.java +++ b/src/main/java/gyro/azure/network/RequestRoutingRule.java @@ -16,12 +16,12 @@ package gyro.azure.network; -import com.microsoft.azure.management.network.ApplicationGateway.Update; -import com.microsoft.azure.management.network.ApplicationGatewayRequestRoutingRule; -import com.microsoft.azure.management.network.ApplicationGatewayRequestRoutingRule.UpdateDefinitionStages.WithBackendHttpConfigOrRedirect; -import com.microsoft.azure.management.network.ApplicationGatewayRequestRoutingRule.DefinitionStages; -import com.microsoft.azure.management.network.ApplicationGateway.DefinitionStages.WithRequestRoutingRuleOrCreate; -import com.microsoft.azure.management.network.ApplicationGateway.DefinitionStages.WithRequestRoutingRule; +import com.azure.resourcemanager.network.models.ApplicationGateway.DefinitionStages.WithRequestRoutingRule; +import com.azure.resourcemanager.network.models.ApplicationGateway.DefinitionStages.WithRequestRoutingRuleOrCreate; +import com.azure.resourcemanager.network.models.ApplicationGateway.Update; +import com.azure.resourcemanager.network.models.ApplicationGatewayRequestRoutingRule; +import com.azure.resourcemanager.network.models.ApplicationGatewayRequestRoutingRule.DefinitionStages; +import com.azure.resourcemanager.network.models.ApplicationGatewayRequestRoutingRule.UpdateDefinitionStages.WithBackendHttpConfigOrRedirect; import com.psddev.dari.util.ObjectUtils; import gyro.azure.Copyable; import gyro.core.resource.Diffable; @@ -44,6 +44,7 @@ * end */ public class RequestRoutingRule extends Diffable implements Copyable { + private String name; private String listener; private String backend; @@ -115,7 +116,8 @@ public void setRedirectConfiguration(String redirectConfiguration) { public void copyFrom(ApplicationGatewayRequestRoutingRule rule) { setBackend(rule.backend() != null ? rule.backend().name() : null); setListener(rule.listener() != null ? rule.listener().name() : null); - setBackendHttpConfiguration(rule.backendHttpConfiguration() != null ? rule.backendHttpConfiguration().name() : null); + setBackendHttpConfiguration( + rule.backendHttpConfiguration() != null ? rule.backendHttpConfiguration().name() : null); setRedirectConfiguration(rule.redirectConfiguration() != null ? rule.redirectConfiguration().name() : null); setName(rule.name()); } @@ -125,7 +127,9 @@ public String primaryKey() { return getName(); } - WithRequestRoutingRuleOrCreate createRequestRoutingRule(WithRequestRoutingRule preAttach, WithRequestRoutingRuleOrCreate attach) { + WithRequestRoutingRuleOrCreate createRequestRoutingRule( + WithRequestRoutingRule preAttach, + WithRequestRoutingRuleOrCreate attach) { DefinitionStages.WithBackendHttpConfigOrRedirect partialAttach; if (attach == null) { partialAttach = preAttach.defineRequestRoutingRule(getName()).fromListener(getListener()); diff --git a/src/main/java/gyro/azure/network/RouteResource.java b/src/main/java/gyro/azure/network/RouteResource.java index abb4ea47..dcaefd90 100644 --- a/src/main/java/gyro/azure/network/RouteResource.java +++ b/src/main/java/gyro/azure/network/RouteResource.java @@ -16,7 +16,7 @@ package gyro.azure.network; -import com.microsoft.azure.management.network.Route; +import com.azure.resourcemanager.network.models.Route; import gyro.azure.Copyable; import gyro.core.resource.Diffable; import gyro.core.resource.Updatable; @@ -39,6 +39,7 @@ * end */ public class RouteResource extends Diffable implements Copyable { + private String destinationAddressPrefix; private String name; private String nextHopIpAddress; @@ -85,7 +86,7 @@ public void setNextHopIpAddress(String nextHopIpAddress) { * The type of the next hop. */ @Required - @ValidStrings({"Internet", "VirtualAppliance", "VnetLocal", "VirtualNetworkGateway", "None"}) + @ValidStrings({ "Internet", "VirtualAppliance", "VnetLocal", "VirtualNetworkGateway", "None" }) @Updatable public String getNextHopType() { return nextHopType; @@ -104,7 +105,7 @@ public String primaryKey() { public void copyFrom(Route route) { setDestinationAddressPrefix(route.destinationAddressPrefix()); setName(route.name()); - setNextHopIpAddress(route.nextHopIPAddress()); + setNextHopIpAddress(route.nextHopIpAddress()); setNextHopType(route.nextHopType().toString()); } } diff --git a/src/main/java/gyro/azure/network/RouteTableFinder.java b/src/main/java/gyro/azure/network/RouteTableFinder.java index 27935cac..69943124 100644 --- a/src/main/java/gyro/azure/network/RouteTableFinder.java +++ b/src/main/java/gyro/azure/network/RouteTableFinder.java @@ -16,14 +16,15 @@ package gyro.azure.network; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.network.RouteTable; -import gyro.azure.AzureFinder; -import gyro.core.Type; - import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; + +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.network.models.RouteTable; +import gyro.azure.AzureResourceManagerFinder; +import gyro.core.Type; /** * Query route table. @@ -36,7 +37,8 @@ * route-table: $(external-query azure::route-table {}) */ @Type("route-table") -public class RouteTableFinder extends AzureFinder { +public class RouteTableFinder extends AzureResourceManagerFinder { + private String id; /** @@ -49,13 +51,14 @@ public String getId() { public void setId(String id) { this.id = id; } + @Override - protected List findAllAzure(Azure client) { - return client.routeTables().list(); + protected List findAllAzure(AzureResourceManager client) { + return client.routeTables().list().stream().collect(Collectors.toList()); } @Override - protected List findAzure(Azure client, Map filters) { + protected List findAzure(AzureResourceManager client, Map filters) { RouteTable routeTable = client.routeTables().getById(filters.get("id")); if (routeTable == null) { return Collections.emptyList(); diff --git a/src/main/java/gyro/azure/network/RouteTableResource.java b/src/main/java/gyro/azure/network/RouteTableResource.java index 0bc1c22a..a765aa04 100644 --- a/src/main/java/gyro/azure/network/RouteTableResource.java +++ b/src/main/java/gyro/azure/network/RouteTableResource.java @@ -16,32 +16,29 @@ package gyro.azure.network; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import com.azure.core.management.Region; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.network.models.Route; +import com.azure.resourcemanager.network.models.Route.DefinitionStages.WithNextHopType; +import com.azure.resourcemanager.network.models.RouteNextHopType; +import com.azure.resourcemanager.network.models.RouteTable; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.azure.resources.ResourceGroupResource; import gyro.core.GyroUI; -import gyro.core.resource.Id; -import gyro.core.resource.Updatable; import gyro.core.Type; +import gyro.core.resource.Id; import gyro.core.resource.Output; import gyro.core.resource.Resource; - -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.network.Route; -import com.microsoft.azure.management.network.RouteNextHopType; -import com.microsoft.azure.management.network.RouteTable; -import com.microsoft.azure.management.network.Route.DefinitionStages.WithNextHopType; -import com.microsoft.azure.management.resources.fluentcore.arm.Region; +import gyro.core.resource.Updatable; import gyro.core.scope.State; import gyro.core.validation.Required; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - /** * Creates a route table. * @@ -67,6 +64,7 @@ */ @Type("route-table") public class RouteTableResource extends AzureResource implements Copyable { + private Boolean bgpRoutePropagationDisabled; private String id; private String name; @@ -178,7 +176,7 @@ public void copyFrom(RouteTable routeTable) { @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); RouteTable routeTable = client.routeTables().getById(getId()); @@ -193,14 +191,13 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); RouteTable.DefinitionStages.WithCreate withCreate; withCreate = client.routeTables().define(getName()) .withRegion(Region.fromName(getRegion())) .withExistingResourceGroup(getResourceGroup().getName()); - if (getBgpRoutePropagationDisabled()) { withCreate.withDisableBgpRoutePropagation(); } @@ -223,7 +220,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); RouteTableResource currentResource = (RouteTableResource) current; @@ -258,7 +255,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createResourceManagerClient(); client.routeTables().deleteById(getId()); } diff --git a/src/main/java/gyro/azure/network/SubnetResource.java b/src/main/java/gyro/azure/network/SubnetResource.java index 9caa1721..d60a7daf 100644 --- a/src/main/java/gyro/azure/network/SubnetResource.java +++ b/src/main/java/gyro/azure/network/SubnetResource.java @@ -16,6 +16,15 @@ package gyro.azure.network; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Predicate; +import java.util.stream.Collectors; + import com.azure.core.management.Region; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.network.models.Network; @@ -26,24 +35,12 @@ import gyro.azure.Copyable; import gyro.core.GyroException; import gyro.core.GyroUI; -import gyro.core.resource.Id; import gyro.core.resource.Output; -import gyro.core.resource.Updatable; import gyro.core.resource.Resource; - - +import gyro.core.resource.Updatable; import gyro.core.scope.State; import gyro.core.validation.Required; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Predicate; -import java.util.stream.Collectors; - /** * Creates a subnet. * @@ -147,8 +144,12 @@ public void setId(String id) { public void copyFrom(Subnet subnet) { setAddressPrefix(subnet.addressPrefix()); setName(subnet.name()); - setNetworkSecurityGroup(!ObjectUtils.isBlank(subnet.networkSecurityGroupId()) ? findById(NetworkSecurityGroupResource.class, subnet.networkSecurityGroupId()) : null); - setRouteTable(!ObjectUtils.isBlank(subnet.routeTableId()) ? findById(RouteTableResource.class, subnet.routeTableId()) : null); + setNetworkSecurityGroup(!ObjectUtils.isBlank(subnet.networkSecurityGroupId()) ? findById( + NetworkSecurityGroupResource.class, + subnet.networkSecurityGroupId()) : null); + setRouteTable(!ObjectUtils.isBlank(subnet.routeTableId()) ? findById( + RouteTableResource.class, + subnet.routeTableId()) : null); setServiceEndpoints(toServiceEndpoints(subnet.servicesWithAccess())); } @@ -214,7 +215,8 @@ public void update(GyroUI ui, State state, Resource current, Set changed SubnetResource oldResource = (SubnetResource) current; List addServiceEndpoints = getServiceEndpoints().keySet().stream() - .filter(((Predicate) new HashSet<>(oldResource.getServiceEndpoints().keySet())::contains).negate()) + .filter(((Predicate) new HashSet<>(oldResource.getServiceEndpoints() + .keySet())::contains).negate()) .collect(Collectors.toList()); for (String endpoint : addServiceEndpoints) { @@ -253,7 +255,7 @@ private Map> toServiceEndpoints(Map> endpoints = new HashMap<>(); for (Map.Entry> entry : serviceEndpointMap.entrySet()) { - List regions = new ArrayList<>(); + List regions = new ArrayList<>(); for (Region region : entry.getValue()) { regions.add(region.toString()); } From fe0c9560dffd3e5395a65b779f89f189bd84635d Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Fri, 3 Jun 2022 18:59:13 -0400 Subject: [PATCH 36/43] initial refactor keyvalut --- build.gradle | 3 +- .../java/gyro/azure/AbstractAzureCommand.java | 10 +- .../azure/AzureResourceManagerFinder.java | 5 + .../azure/CloudBlobContainerFileBackend.java | 185 ---------- .../azure/keyvault/AbstractVaultCommand.java | 8 +- .../keyvault/AddVaultCertificateCommand.java | 22 +- .../azure/keyvault/AddVaultSecretCommand.java | 24 +- .../KeyVaultCertificateAttribute.java | 110 ------ .../keyvault/KeyVaultCertificateFinder.java | 34 +- .../KeyVaultCertificateIssuerParameter.java | 70 ---- .../KeyVaultCertificateKeyProperties.java | 118 ------ .../keyvault/KeyVaultCertificateLifetime.java | 74 ++-- .../KeyVaultCertificateLifetimeAction.java | 56 --- .../KeyVaultCertificateLifetimeTrigger.java | 72 ---- .../keyvault/KeyVaultCertificatePolicy.java | 342 +++++++++++++----- .../keyvault/KeyVaultCertificateResource.java | 170 ++++----- .../KeyVaultCertificateSecretProperties.java | 55 --- ...aultCertificateSubjectAlternativeName.java | 16 +- .../KeyVaultCertificateX509Properties.java | 127 ------- .../azure/keyvault/KeyVaultKeyFinder.java | 21 +- .../gyro/azure/keyvault/KeyVaultResource.java | 7 - .../azure/keyvault/KeyVaultSecretFinder.java | 22 +- .../keyvault/ListVaultCertificateCommand.java | 48 ++- .../keyvault/ListVaultSecretCommand.java | 27 +- .../RemoveVaultCertificateCommand.java | 23 +- .../keyvault/RemoveVaultSecretCommand.java | 6 +- .../AbstractApplicationGatewayCommand.java | 28 +- ...dApplicationGatewayCertificateCommand.java | 2 +- ...tApplicationGatewayCertificateCommand.java | 20 +- ...tApplicationGatewayCertificateCommand.java | 2 +- ...eApplicationGatewayCertificateCommand.java | 2 +- 31 files changed, 557 insertions(+), 1152 deletions(-) delete mode 100644 src/main/java/gyro/azure/CloudBlobContainerFileBackend.java delete mode 100644 src/main/java/gyro/azure/keyvault/KeyVaultCertificateAttribute.java delete mode 100644 src/main/java/gyro/azure/keyvault/KeyVaultCertificateIssuerParameter.java delete mode 100644 src/main/java/gyro/azure/keyvault/KeyVaultCertificateKeyProperties.java delete mode 100644 src/main/java/gyro/azure/keyvault/KeyVaultCertificateLifetimeAction.java delete mode 100644 src/main/java/gyro/azure/keyvault/KeyVaultCertificateLifetimeTrigger.java delete mode 100644 src/main/java/gyro/azure/keyvault/KeyVaultCertificateSecretProperties.java delete mode 100644 src/main/java/gyro/azure/keyvault/KeyVaultCertificateX509Properties.java diff --git a/build.gradle b/build.gradle index a90d5b62..1d1e4e26 100644 --- a/build.gradle +++ b/build.gradle @@ -77,7 +77,7 @@ dependencies { implementation 'org.reflections:reflections:0.9.10' implementation 'com.azure.resourcemanager:azure-resourcemanager:2.14.0' - implementation 'com.azure:azure-security-keyvault-certificates:4.3.1' + implementation 'com.azure:azure-security-keyvault-certificates:4.3.2' implementation 'com.azure:azure-data-tables:12.3.0' implementation 'com.azure:azure-storage-queue:12.12.2' implementation 'com.azure:azure-storage-file-share:12.12.2' @@ -85,6 +85,7 @@ dependencies { implementation 'com.azure:azure-identity:1.5.0' implementation 'com.azure:azure-core-http-okhttp:1.8.0' runtimeOnly 'com.nimbusds:oauth2-oidc-sdk:9.34' + implementation 'com.azure:azure-security-keyvault-certificates:4.3.2' gyroDoclet 'gyro:gyro-doclet:1.0.0' } diff --git a/src/main/java/gyro/azure/AbstractAzureCommand.java b/src/main/java/gyro/azure/AbstractAzureCommand.java index 0f56ea23..575407eb 100644 --- a/src/main/java/gyro/azure/AbstractAzureCommand.java +++ b/src/main/java/gyro/azure/AbstractAzureCommand.java @@ -25,8 +25,8 @@ import java.util.stream.Collectors; import java.util.stream.Stream; +import com.azure.core.credential.TokenCredential; import com.azure.resourcemanager.AzureResourceManager; -import com.microsoft.azure.management.Azure; import gyro.core.GyroCore; import gyro.core.GyroException; import gyro.core.GyroInputStream; @@ -86,7 +86,7 @@ private void setScope() { this.scope = current; } - public Azure getClient() { + public AzureResourceManager getResourceManagerClient() { Credentials credentials = getScope().getSettings(CredentialsSettings.class) .getCredentialsByName() .get("azure::" + getCredential()); @@ -97,10 +97,10 @@ public Azure getClient() { getCredential())); } - return AzureResource.createClient((AzureCredentials) credentials); + return AzureResource.createResourceManagerClient((AzureCredentials) credentials); } - public AzureResourceManager getResourceManagerClient() { + public TokenCredential getTokenCredential() { Credentials credentials = getScope().getSettings(CredentialsSettings.class) .getCredentialsByName() .get("azure::" + getCredential()); @@ -111,7 +111,7 @@ public AzureResourceManager getResourceManagerClient() { getCredential())); } - return AzureResource.createResourceManagerClient((AzureCredentials) credentials); + return AzureResource.getTokenCredential((AzureCredentials) credentials); } private void evaluateFile(String file, Consumer consumer, RootScope current) { diff --git a/src/main/java/gyro/azure/AzureResourceManagerFinder.java b/src/main/java/gyro/azure/AzureResourceManagerFinder.java index af07e2cf..6208756b 100644 --- a/src/main/java/gyro/azure/AzureResourceManagerFinder.java +++ b/src/main/java/gyro/azure/AzureResourceManagerFinder.java @@ -21,6 +21,7 @@ import java.util.Map; import java.util.stream.Collectors; +import com.azure.core.credential.TokenCredential; import com.azure.resourcemanager.AzureResourceManager; import gyro.core.finder.Finder; @@ -47,6 +48,10 @@ private AzureResourceManager newClient() { return AzureResource.createResourceManagerClient(credentials(AzureCredentials.class)); } + protected TokenCredential getTokenCredential() { + return AzureResource.getTokenCredential(credentials(AzureCredentials.class)); + } + @SuppressWarnings("unchecked") private R newResource(M model) { R resource = newResource(); diff --git a/src/main/java/gyro/azure/CloudBlobContainerFileBackend.java b/src/main/java/gyro/azure/CloudBlobContainerFileBackend.java deleted file mode 100644 index fd853dec..00000000 --- a/src/main/java/gyro/azure/CloudBlobContainerFileBackend.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Copyright 2019, Perfect Sense, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package gyro.azure; - -import java.io.InputStream; -import java.io.OutputStream; -import java.net.URI; -import java.net.URISyntaxException; -import java.security.InvalidKeyException; -import java.util.Optional; -import java.util.stream.Stream; -import java.util.stream.StreamSupport; - -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.storage.StorageAccount; -import com.microsoft.azure.storage.CloudStorageAccount; -import com.microsoft.azure.storage.StorageException; -import com.microsoft.azure.storage.blob.CloudBlobClient; -import com.microsoft.azure.storage.blob.CloudBlobContainer; -import com.microsoft.azure.storage.blob.CloudBlockBlob; -import com.microsoft.azure.storage.blob.CopyStatus; -import com.microsoft.azure.storage.blob.ListBlobItem; -import com.psddev.dari.util.StringUtils; -import gyro.azure.storage.StorageAccountResource; -import gyro.core.FileBackend; -import gyro.core.GyroCore; -import gyro.core.GyroException; -import gyro.core.Type; - -@Type("cloud-blob-container") -public class CloudBlobContainerFileBackend extends FileBackend { - - private String storageAccount; - private String cloudBlobContainer; - private String resourceGroup; - private String prefix; - - public String getStorageAccount() { - return storageAccount; - } - - public void setStorageAccount(String storageAccount) { - this.storageAccount = storageAccount; - } - - public String getCloudBlobContainer() { - return cloudBlobContainer; - } - - public void setCloudBlobContainer(String cloudBlobContainer) { - this.cloudBlobContainer = cloudBlobContainer; - } - - public String getPrefix() { - return prefix; - } - - public void setPrefix(String prefix) { - this.prefix = prefix; - } - - public String getResourceGroup() { - return resourceGroup; - } - - public void setResourceGroup(String resourceGroup) { - this.resourceGroup = resourceGroup; - } - - @Override - public Stream list() throws Exception { - if (this.equals(GyroCore.getStateBackend(getName()))) { - return StreamSupport.stream(container().listBlobs(getPrefix(), true).spliterator(), false) - .map(ListBlobItem::getUri) - .map(URI::getPath) - .filter(f -> f.endsWith(".gyro")) - .map(this::removeContainerAndPrefix); - } - - return Stream.empty(); - } - - @Override - public InputStream openInput(String file) throws Exception { - return getBlockBlobReference(file).openInputStream(); - } - - @Override - public OutputStream openOutput(String file) throws Exception { - return getBlockBlobReference(file).openOutputStream(); - } - - @Override - public void delete(String file) throws Exception { - getBlockBlobReference(file).deleteIfExists(); - } - - @Override - public boolean exists(String file) throws Exception { - return getBlockBlobReference(file).exists(); - } - - @Override - public void copy(String source, String destination) throws Exception { - CloudBlockBlob target = getBlockBlobReference(destination); - target.startCopy(getBlockBlobReference(source)); - - long wait = 0L; - - while (true) { - target.downloadAttributes(); - CopyStatus copyStatus = target.getCopyState().getStatus(); - - if (copyStatus != CopyStatus.PENDING) { - if (copyStatus != CopyStatus.SUCCESS) { - throw new GyroException( - String.format("Copying %s to %s failed: %s", source, destination, copyStatus)); - } - break; - } - wait += 1000L; - Thread.sleep(wait); - } - } - - private CloudBlobContainer container() { - String account = getStorageAccount(); - StorageAccount storageAccount = Optional.ofNullable(getCredentials("azure")) - .filter(AzureCredentials.class::isInstance) - .map(AzureCredentials.class::cast) - .map(AzureResource::createClient) - .map(Azure::storageAccounts) - .map(e -> e.getByResourceGroup(getResourceGroup(), account)) - .orElseThrow(() -> new GyroException("No storage account available!")); - StorageAccountResource storage = getRootScope().findResourceById(StorageAccountResource.class, account); - // storage.copyFrom(storageAccount); // TODO handle this - - try { - CloudStorageAccount cloudStorageAccount = CloudStorageAccount.parse(storage.getConnection()); - CloudBlobClient blobClient = cloudStorageAccount.createCloudBlobClient(); - - return blobClient.getContainerReference(getCloudBlobContainer()); - } catch (StorageException | URISyntaxException | InvalidKeyException ex) { - throw new GyroException(ex.getMessage()); - } - } - - private String prefixed(String file) { - return getPrefix() != null ? getPrefix() + '/' + file : file; - } - - private String removeContainerAndPrefix(String file) { - String cloudBlobContainer = getCloudBlobContainer(); - - if (StringUtils.isBlank(cloudBlobContainer)) { - throw new IllegalStateException("container can't be null."); - } - - file = StringUtils.removeStart(file, "/" + cloudBlobContainer + "/"); - - if (getPrefix() != null && file.startsWith(getPrefix() + "/")) { - return file.substring(getPrefix().length() + 1); - } - - return file; - } - - private CloudBlockBlob getBlockBlobReference(String file) throws Exception { - return container().getBlockBlobReference(prefixed(file)); - } -} diff --git a/src/main/java/gyro/azure/keyvault/AbstractVaultCommand.java b/src/main/java/gyro/azure/keyvault/AbstractVaultCommand.java index 1ae025e1..775b8077 100644 --- a/src/main/java/gyro/azure/keyvault/AbstractVaultCommand.java +++ b/src/main/java/gyro/azure/keyvault/AbstractVaultCommand.java @@ -18,8 +18,8 @@ import java.util.concurrent.Callable; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.keyvault.Vault; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.keyvault.models.Vault; import gyro.azure.AbstractAzureCommand; import gyro.core.GyroException; import gyro.core.command.GyroCommand; @@ -28,7 +28,7 @@ public abstract class AbstractVaultCommand extends AbstractAzureCommand implements GyroCommand, Callable { - public static Vault getVault(String vaultResourceName, RootScope scope, Azure client) { + public static Vault getVault(String vaultResourceName, RootScope scope, AzureResourceManager client) { Resource resource = scope.findResource("azure::key-vault::" + vaultResourceName); if (resource instanceof KeyVaultResource) { @@ -47,7 +47,7 @@ public static Vault getVault(String vaultResourceName, RootScope scope, Azure cl Vault getVault(String vaultResourceName) { RootScope scope = getScope(); - Azure client = getClient(); + AzureResourceManager client = getResourceManagerClient(); return getVault(vaultResourceName, scope, client); } diff --git a/src/main/java/gyro/azure/keyvault/AddVaultCertificateCommand.java b/src/main/java/gyro/azure/keyvault/AddVaultCertificateCommand.java index 990198ee..c0e7d04e 100644 --- a/src/main/java/gyro/azure/keyvault/AddVaultCertificateCommand.java +++ b/src/main/java/gyro/azure/keyvault/AddVaultCertificateCommand.java @@ -18,11 +18,13 @@ import java.nio.file.Files; import java.nio.file.Paths; -import java.util.Base64; import java.util.List; -import com.microsoft.azure.keyvault.requests.ImportCertificateRequest; -import com.microsoft.azure.management.keyvault.Vault; +import com.azure.resourcemanager.keyvault.models.Vault; +import com.azure.security.keyvault.certificates.CertificateClient; +import com.azure.security.keyvault.certificates.CertificateClientBuilder; +import com.azure.security.keyvault.certificates.models.ImportCertificateOptions; +import com.azure.security.keyvault.certificates.models.KeyVaultCertificateWithPolicy; import com.psddev.dari.util.ObjectUtils; import gyro.core.GyroCore; import gyro.core.GyroException; @@ -53,16 +55,20 @@ public void execute() throws Exception { Vault vault = getVault(vaultResourceName); - ImportCertificateRequest.Builder builder = new ImportCertificateRequest.Builder( - vault.vaultUri(), + CertificateClient client = new CertificateClientBuilder() + .vaultUrl(vault.vaultUri()) + .credential(getTokenCredential()) + .buildClient(); + + ImportCertificateOptions certificateOptions = new ImportCertificateOptions( certificateName, - Base64.getEncoder().encodeToString(Files.readAllBytes(Paths.get(certificatePath)))); + Files.readAllBytes(Paths.get(certificatePath))); if (!ObjectUtils.isBlank(password)) { - builder = builder.withPassword(password); + certificateOptions.setPassword(password); } - vault.client().importCertificate(builder.build()); + KeyVaultCertificateWithPolicy policy = client.importCertificate(certificateOptions); GyroCore.ui().write("\nCertificate added."); } else { diff --git a/src/main/java/gyro/azure/keyvault/AddVaultSecretCommand.java b/src/main/java/gyro/azure/keyvault/AddVaultSecretCommand.java index c553c154..c9079b2e 100644 --- a/src/main/java/gyro/azure/keyvault/AddVaultSecretCommand.java +++ b/src/main/java/gyro/azure/keyvault/AddVaultSecretCommand.java @@ -1,10 +1,11 @@ package gyro.azure.keyvault; +import java.time.ZoneOffset; import java.util.List; -import com.microsoft.azure.keyvault.models.SecretAttributes; -import com.microsoft.azure.keyvault.requests.SetSecretRequest; -import com.microsoft.azure.management.keyvault.Vault; +import com.azure.resourcemanager.keyvault.models.Secret; +import com.azure.resourcemanager.keyvault.models.Vault; +import com.azure.security.keyvault.secrets.models.SecretProperties; import com.psddev.dari.util.ObjectUtils; import gyro.core.GyroCore; import gyro.core.GyroException; @@ -45,19 +46,22 @@ public void execute() throws Exception { Vault vault = getVault(vaultResourceName); - SetSecretRequest.Builder builder = new SetSecretRequest.Builder(vault.vaultUri(), secretName, secretValue); + Secret.DefinitionStages.WithCreate withCreate = vault.secrets().define(secretName).withValue(secretValue); - SecretAttributes attributes = new SecretAttributes(); + SecretProperties properties = new SecretProperties(); if (!ObjectUtils.isBlank(contentType)) { - builder = builder.withContentType(contentType); + properties.setContentType(contentType); + withCreate = withCreate.withContentType(contentType); } - builder = builder.withAttributes(attributes.withEnabled(enabled) - .withExpires(expires != null ? DateTime.parse(expires) : null) - .withNotBefore(notBefore != null ? DateTime.parse(notBefore) : null)); + properties.setEnabled(enabled); + properties.setExpiresOn(DateTime.parse(expires).toDate().toInstant().atOffset(ZoneOffset.UTC)); + properties.setNotBefore(DateTime.parse(notBefore).toDate().toInstant().atOffset(ZoneOffset.UTC)); + + withCreate = withCreate.withAttributes(properties); + withCreate.create(); - vault.client().setSecret(builder.build()); GyroCore.ui().write("\nSecret added."); } else { diff --git a/src/main/java/gyro/azure/keyvault/KeyVaultCertificateAttribute.java b/src/main/java/gyro/azure/keyvault/KeyVaultCertificateAttribute.java deleted file mode 100644 index f926a201..00000000 --- a/src/main/java/gyro/azure/keyvault/KeyVaultCertificateAttribute.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright 2020, Perfect Sense, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package gyro.azure.keyvault; - -import com.microsoft.azure.keyvault.models.CertificateAttributes; -import gyro.azure.Copyable; -import gyro.core.resource.Diffable; -import gyro.core.resource.Output; -import org.joda.time.DateTime; - -public class KeyVaultCertificateAttribute extends Diffable implements Copyable { - - private Boolean enabled; - private String expires; - private String notBefore; - private String created; - private String updated; - - /** - * Enable or Disable the certificate for use. - */ - public Boolean getEnabled() { - return enabled; - } - - public void setEnabled(Boolean enabled) { - this.enabled = enabled; - } - - /** - * A date time value value in UTC specifying when the certificate expires. Format ``YYYY-MM-DDTHH:MM:SS.sssZ``. Example ``2020-04-03T15:54:12.000Z``. - */ - public String getExpires() { - return expires; - } - - public void setExpires(String expires) { - this.expires = expires; - } - - /** - * A date time value value in UTC specifying the not before time. Format ``YYYY-MM-DDTHH:MM:SS.sssZ``. Example ``2020-04-03T15:54:12.000Z``. - */ - public String getNotBefore() { - return notBefore; - } - - public void setNotBefore(String notBefore) { - this.notBefore = notBefore; - } - - /** - * The date time value in UTC of when the certificate was created. - */ - @Output - public String getCreated() { - return created; - } - - public void setCreated(String created) { - this.created = created; - } - - /** - * The date time value in UTC of when the certificate was last updated. - */ - @Output - public String getUpdated() { - return updated; - } - - public void setUpdated(String updated) { - this.updated = updated; - } - - @Override - public String primaryKey() { - return ""; - } - - CertificateAttributes toAttributes() { - return (CertificateAttributes) new CertificateAttributes() - .withEnabled(getEnabled()) - .withExpires(getExpires() != null ? DateTime.parse(getExpires()) : null) - .withNotBefore(getNotBefore() != null ? DateTime.parse(getNotBefore()) : null); - } - - @Override - public void copyFrom(CertificateAttributes attributes) { - setEnabled(attributes.enabled()); - setExpires(attributes.expires() != null ? attributes.expires().toString() : null); - setNotBefore(attributes.notBefore() != null ? attributes.notBefore().toString() : null); - setCreated(attributes.created() != null ? attributes.created().toString() : null); - setUpdated(attributes.updated() != null ? attributes.updated().toString() : null); - } -} diff --git a/src/main/java/gyro/azure/keyvault/KeyVaultCertificateFinder.java b/src/main/java/gyro/azure/keyvault/KeyVaultCertificateFinder.java index 2b7458e0..1d9677e7 100644 --- a/src/main/java/gyro/azure/keyvault/KeyVaultCertificateFinder.java +++ b/src/main/java/gyro/azure/keyvault/KeyVaultCertificateFinder.java @@ -20,10 +20,13 @@ import java.util.List; import java.util.Map; -import com.microsoft.azure.keyvault.models.CertificateBundle; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.keyvault.Vault; -import gyro.azure.AzureFinder; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.keyvault.models.Vault; +import com.azure.security.keyvault.certificates.CertificateClient; +import com.azure.security.keyvault.certificates.CertificateClientBuilder; +import com.azure.security.keyvault.certificates.models.KeyVaultCertificateWithPolicy; +import gyro.azure.AzureResourceManagerFinder; import gyro.core.Type; /** @@ -37,7 +40,7 @@ * certificate: $(external-query azure::key-vault-certificate {resource-group: "resource-group-example", vault: "vault-example", name: "certificate-example"}) */ @Type("key-vault-certificate") -public class KeyVaultCertificateFinder extends AzureFinder { +public class KeyVaultCertificateFinder extends AzureResourceManagerFinder { private String resourceGroup; private String vault; @@ -77,17 +80,28 @@ public void setName(String name) { } @Override - protected List findAllAzure(Azure client) { + protected List findAllAzure(AzureResourceManager client) { throw new UnsupportedOperationException("Finding all certificates without any filter is not supported!!"); } @Override - protected List findAzure(Azure client, Map filters) { - List certificateBundles = new ArrayList<>(); + protected List findAzure(AzureResourceManager client, Map filters) { + List certificates = new ArrayList<>(); Vault vault = client.vaults().getByResourceGroup(filters.get("resource-group"), filters.get("vault")); if (vault != null) { - certificateBundles.add(vault.client().getCertificate(vault.vaultUri(), filters.get("name"))); + CertificateClient certificateClient = new CertificateClientBuilder() + .vaultUrl(vault.vaultUri()) + .credential(getTokenCredential()) + .buildClient(); + + try { + KeyVaultCertificateWithPolicy certificate = certificateClient.getCertificate(filters.get("name")); + certificates.add(certificate); + } catch (ResourceNotFoundException ex) { + // ignore + } } - return certificateBundles; + + return certificates; } } diff --git a/src/main/java/gyro/azure/keyvault/KeyVaultCertificateIssuerParameter.java b/src/main/java/gyro/azure/keyvault/KeyVaultCertificateIssuerParameter.java deleted file mode 100644 index bf33968e..00000000 --- a/src/main/java/gyro/azure/keyvault/KeyVaultCertificateIssuerParameter.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright 2020, Perfect Sense, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package gyro.azure.keyvault; - -import com.microsoft.azure.keyvault.models.IssuerParameters; -import gyro.azure.Copyable; -import gyro.core.resource.Diffable; -import gyro.core.validation.Required; - -public class KeyVaultCertificateIssuerParameter extends Diffable implements Copyable { - - private String name; - private String type; - - /** - * The name of the issuer of the certificate. Valid values are ``Self``, ``Unknown`` or any issuer already present in your azure account as a valid CA. - * - * @no-doc ValidStrings - */ - @Required - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - /** - * Type of certificate being issued. - */ - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - @Override - public String primaryKey() { - return ""; - } - - IssuerParameters toIssuerParameters() { - return new IssuerParameters() - .withCertificateType(getType()) - .withName(getName()); - } - - @Override - public void copyFrom(IssuerParameters issuerParameters) { - setName(issuerParameters.name()); - setType(issuerParameters.certificateType()); - } -} diff --git a/src/main/java/gyro/azure/keyvault/KeyVaultCertificateKeyProperties.java b/src/main/java/gyro/azure/keyvault/KeyVaultCertificateKeyProperties.java deleted file mode 100644 index 704faa5b..00000000 --- a/src/main/java/gyro/azure/keyvault/KeyVaultCertificateKeyProperties.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright 2020, Perfect Sense, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package gyro.azure.keyvault; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; -import java.util.stream.Stream; - -import com.microsoft.azure.keyvault.models.KeyProperties; -import gyro.azure.Copyable; -import gyro.core.resource.Diffable; -import gyro.core.validation.Required; -import gyro.core.validation.ValidNumbers; -import gyro.core.validation.ValidStrings; -import gyro.core.validation.ValidationError; - -public class KeyVaultCertificateKeyProperties extends Diffable implements Copyable { - - private Boolean exportable; - private Boolean reuseKey; - private Integer size; - private String type; - - /** - * When set to ``true`` allows the certificates private key to be exportable. - */ - @Required - public Boolean getExportable() { - return exportable; - } - - public void setExportable(Boolean exportable) { - this.exportable = exportable; - } - - /** - * When set to ``true`` allows the certificate key to be reused or renewed. - */ - @Required - public Boolean getReuseKey() { - return reuseKey; - } - - public void setReuseKey(Boolean reuseKey) { - this.reuseKey = reuseKey; - } - - /** - * The key size. - */ - @ValidNumbers({2048, 3072, 4096}) - public Integer getSize() { - return size; - } - - public void setSize(Integer size) { - this.size = size; - } - - /** - * The key type. Currently only supported value is ``RSA``. - */ - @ValidStrings("RSA") - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - @Override - public String primaryKey() { - return ""; - } - - KeyProperties toKeyProperties() { - return new KeyProperties() - .withReuseKey(getReuseKey()) - .withKeyType(getType()) - .withKeySize(getSize()) - .withExportable(getExportable()); - } - - @Override - public void copyFrom(KeyProperties keyProperties) { - setExportable(keyProperties.exportable()); - setReuseKey(keyProperties.reuseKey()); - setType(keyProperties.keyType()); - setSize(keyProperties.keySize()); - } - - @Override - public List validate(Set configuredFields) { - List errors = new ArrayList<>(); - - if (getSize() != null && configuredFields.contains("size") && Stream.of(2048, 3072, 4096).noneMatch(o -> getSize().equals(o))) { - errors.add(new ValidationError(this, "size", "Valid value for `size` are 2048, 3072 or 4096")); - } - - return errors; - } -} diff --git a/src/main/java/gyro/azure/keyvault/KeyVaultCertificateLifetime.java b/src/main/java/gyro/azure/keyvault/KeyVaultCertificateLifetime.java index 57142054..93b848d4 100644 --- a/src/main/java/gyro/azure/keyvault/KeyVaultCertificateLifetime.java +++ b/src/main/java/gyro/azure/keyvault/KeyVaultCertificateLifetime.java @@ -16,68 +16,76 @@ package gyro.azure.keyvault; -import java.util.Optional; - -import com.microsoft.azure.keyvault.models.LifetimeAction; +import com.azure.security.keyvault.certificates.models.CertificatePolicyAction; +import com.azure.security.keyvault.certificates.models.LifetimeAction; import gyro.azure.Copyable; import gyro.core.resource.Diffable; +import gyro.core.validation.Min; +import gyro.core.validation.Range; import gyro.core.validation.Required; +import gyro.core.validation.ValidStrings; public class KeyVaultCertificateLifetime extends Diffable implements Copyable { - private KeyVaultCertificateLifetimeAction action; - private KeyVaultCertificateLifetimeTrigger trigger; + private String action; + private Integer daysBeforeExpiry; + private Integer lifetimePercentage; /** - * Lifetime action config for the certificate policy. - * - * @subresource gyro.azure.keyvault.KeyVaultCertificateLifetimeAction + * The lifetime action type. */ + @ValidStrings({"EmailContacts", "AutoRenew"}) @Required - public KeyVaultCertificateLifetimeAction getAction() { + public String getAction() { return action; } - public void setAction(KeyVaultCertificateLifetimeAction action) { + public void setAction(String action) { this.action = action; } /** - * Lifetime trigger config for the certificate policy. - * - * @subresource gyro.azure.keyvault.KeyVaultCertificateLifetimeTrigger + * Days before certificate expires of lifetime at which to trigger. + */ + @Min(0) + public Integer getDaysBeforeExpiry() { + return daysBeforeExpiry; + } + + public void setDaysBeforeExpiry(Integer daysBeforeExpiry) { + this.daysBeforeExpiry = daysBeforeExpiry; + } + + /** + * Percentage of lifetime at which to trigger. Value should be between ``1`` and ``99``. */ - public KeyVaultCertificateLifetimeTrigger getTrigger() { - return trigger; + @Required + @Range(min = 1, max = 99) + public Integer getLifetimePercentage() { + return lifetimePercentage; } - public void setTrigger(KeyVaultCertificateLifetimeTrigger trigger) { - this.trigger = trigger; + public void setLifetimePercentage(Integer lifetimePercentage) { + this.lifetimePercentage = lifetimePercentage; } @Override public String primaryKey() { - return String.format("with action - %s", getAction().getType()); + return String.format("with action - %s", getAction()); } LifetimeAction toLifetimeAction() { - return new LifetimeAction() - .withAction(getAction() != null ? getAction().toAction() : null) - .withTrigger(getTrigger() != null ? getTrigger().totTrigger() : null); + LifetimeAction lifetimeAction = new LifetimeAction(CertificatePolicyAction.fromString(getAction())); + lifetimeAction.setLifetimePercentage(getLifetimePercentage()); + lifetimeAction.setDaysBeforeExpiry(getDaysBeforeExpiry()); + + return lifetimeAction; } @Override - public void copyFrom(LifetimeAction lifetimeAction) { - setAction(Optional.ofNullable(lifetimeAction.action()).map(o -> { - KeyVaultCertificateLifetimeAction action = newSubresource(KeyVaultCertificateLifetimeAction.class); - action.copyFrom(o); - return action; - }).orElse(null)); - - setTrigger(Optional.ofNullable(lifetimeAction.trigger()).map(o -> { - KeyVaultCertificateLifetimeTrigger trigger = newSubresource(KeyVaultCertificateLifetimeTrigger.class); - trigger.copyFrom(o); - return trigger; - }).orElse(null)); + public void copyFrom(LifetimeAction action) { + setAction(action.getAction().toString()); + setLifetimePercentage(action.getLifetimePercentage()); + setDaysBeforeExpiry(action.getDaysBeforeExpiry()); } } diff --git a/src/main/java/gyro/azure/keyvault/KeyVaultCertificateLifetimeAction.java b/src/main/java/gyro/azure/keyvault/KeyVaultCertificateLifetimeAction.java deleted file mode 100644 index 33439603..00000000 --- a/src/main/java/gyro/azure/keyvault/KeyVaultCertificateLifetimeAction.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright 2020, Perfect Sense, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package gyro.azure.keyvault; - -import com.microsoft.azure.keyvault.models.Action; -import com.microsoft.azure.keyvault.models.ActionType; -import gyro.azure.Copyable; -import gyro.core.resource.Diffable; -import gyro.core.validation.Required; -import gyro.core.validation.ValidStrings; - -public class KeyVaultCertificateLifetimeAction extends Diffable implements Copyable { - - private ActionType type; - - /** - * The lifetime action type. - */ - @Required - @ValidStrings({"EmailContacts", "AutoRenew"}) - public ActionType getType() { - return type; - } - - public void setType(ActionType type) { - this.type = type; - } - - @Override - public String primaryKey() { - return ""; - } - - Action toAction() { - return new Action().withActionType(getType()); - } - - @Override - public void copyFrom(Action action) { - setType(action.actionType()); - } -} diff --git a/src/main/java/gyro/azure/keyvault/KeyVaultCertificateLifetimeTrigger.java b/src/main/java/gyro/azure/keyvault/KeyVaultCertificateLifetimeTrigger.java deleted file mode 100644 index 64f651ce..00000000 --- a/src/main/java/gyro/azure/keyvault/KeyVaultCertificateLifetimeTrigger.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2020, Perfect Sense, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package gyro.azure.keyvault; - -import com.microsoft.azure.keyvault.models.Trigger; -import gyro.azure.Copyable; -import gyro.core.resource.Diffable; -import gyro.core.validation.Min; -import gyro.core.validation.Range; -import gyro.core.validation.Required; - -public class KeyVaultCertificateLifetimeTrigger extends Diffable implements Copyable { - - private Integer daysBeforeExpiry; - private Integer lifetimePercentage; - - /** - * Days before certificate expires of lifetime at which to trigger. - */ - @Min(0) - public Integer getDaysBeforeExpiry() { - return daysBeforeExpiry; - } - - public void setDaysBeforeExpiry(Integer daysBeforeExpiry) { - this.daysBeforeExpiry = daysBeforeExpiry; - } - - /** - * Percentage of lifetime at which to trigger. Value should be between ``1`` and ``99``. - */ - @Required - @Range(min = 1, max = 99) - public Integer getLifetimePercentage() { - return lifetimePercentage; - } - - public void setLifetimePercentage(Integer lifetimePercentage) { - this.lifetimePercentage = lifetimePercentage; - } - - @Override - public String primaryKey() { - return ""; - } - - Trigger totTrigger() { - return new Trigger() - .withDaysBeforeExpiry(getDaysBeforeExpiry()) - .withLifetimePercentage(getLifetimePercentage()); - } - - @Override - public void copyFrom(Trigger trigger) { - setDaysBeforeExpiry(trigger.daysBeforeExpiry()); - setLifetimePercentage(trigger.daysBeforeExpiry()); - } -} diff --git a/src/main/java/gyro/azure/keyvault/KeyVaultCertificatePolicy.java b/src/main/java/gyro/azure/keyvault/KeyVaultCertificatePolicy.java index 527d1c25..48f690c7 100644 --- a/src/main/java/gyro/azure/keyvault/KeyVaultCertificatePolicy.java +++ b/src/main/java/gyro/azure/keyvault/KeyVaultCertificatePolicy.java @@ -17,151 +17,304 @@ package gyro.azure.keyvault; import java.util.ArrayList; +import java.util.Date; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; -import com.microsoft.azure.keyvault.models.CertificatePolicy; +import com.azure.core.util.ExpandableStringEnum; +import com.azure.security.keyvault.certificates.models.CertificateContentType; +import com.azure.security.keyvault.certificates.models.CertificateKeyCurveName; +import com.azure.security.keyvault.certificates.models.CertificateKeyType; +import com.azure.security.keyvault.certificates.models.CertificateKeyUsage; +import com.azure.security.keyvault.certificates.models.CertificatePolicy; +import com.azure.security.keyvault.certificates.models.LifetimeAction; import gyro.azure.Copyable; import gyro.core.resource.Diffable; +import gyro.core.resource.Output; import gyro.core.validation.CollectionMax; +import gyro.core.validation.Range; import gyro.core.validation.Required; +import gyro.core.validation.ValidNumbers; +import gyro.core.validation.ValidStrings; public class KeyVaultCertificatePolicy extends Diffable implements Copyable { - private KeyVaultCertificateIssuerParameter issuerParameter; - private KeyVaultCertificateKeyProperties keyProperties; + private String certificateType; + private String contentType; + private String issuerName; + private String subject; + private String keyType; + private String keyCurveName; + private Boolean enabled; + private Boolean transparent; + private Boolean exportable; + private Boolean keyReusable; + + private Integer validityInMonths; + private Integer keySize; + private Date createdOn; + private Date updatedOn; + private KeyVaultCertificateSubjectAlternativeName subjectAlternativeName; + private List keyUsage; + private List enhancedKeyUsage; private List lifetimeAction; - private KeyVaultCertificateSecretProperties secretProperties; - private KeyVaultCertificateX509Properties x509Properties; - private KeyVaultCertificateAttribute attribute; + + public String getCertificateType() { + return certificateType; + } + + public void setCertificateType(String certificateType) { + this.certificateType = certificateType; + } /** - * Issuer parameter config for the certificate policy. - * - * @subresource gyro.azure.keyvault.KeyVaultCertificateIssuerParameter + * The type of certificate to generate. */ @Required - public KeyVaultCertificateIssuerParameter getIssuerParameter() { - return issuerParameter; + @ValidStrings({"application/x-pem-file", "application/x-pkcs12"}) + public String getContentType() { + return contentType; } - public void setIssuerParameter(KeyVaultCertificateIssuerParameter issuerParameter) { - this.issuerParameter = issuerParameter; + public void setContentType(String contentType) { + this.contentType = contentType; } /** - * The key properties for the certificate policy. + * The name of the issuer of the certificate. Valid values are ``Self``, ``Unknown`` or any issuer already present in your azure account as a valid CA. * - * @subresource gyro.azure.keyvault.KeyVaultCertificateKeyProperties + * @no-doc ValidStrings + */ + @Output + public String getIssuerName() { + return issuerName; + } + + public void setIssuerName(String issuerName) { + this.issuerName = issuerName; + } + + /** + * The x.500 distinguished name. */ @Required - public KeyVaultCertificateKeyProperties getKeyProperties() { - return keyProperties; + public String getSubject() { + return subject; } - public void setKeyProperties(KeyVaultCertificateKeyProperties keyProperties) { - this.keyProperties = keyProperties; + public void setSubject(String subject) { + this.subject = subject; } /** - * Lifetime config for the certificate policy. - * - * @subresource gyro.azure.keyvault.KeyVaultCertificateLifetime + * The key type. Currently only supported value is ``RSA``. + */ + @ValidStrings("RSA") + public String getKeyType() { + return keyType; + } + + public void setKeyType(String keyType) { + this.keyType = keyType; + } + + public String getKeyCurveName() { + return keyCurveName; + } + + public void setKeyCurveName(String keyCurveName) { + this.keyCurveName = keyCurveName; + } + + /** + * Enable or Disable the certificate for use. + */ + public Boolean getEnabled() { + return enabled; + } + + public void setEnabled(Boolean enabled) { + this.enabled = enabled; + } + + public Boolean getTransparent() { + return transparent; + } + + public void setTransparent(Boolean transparent) { + this.transparent = transparent; + } + + /** + * When set to ``true`` allows the certificates private key to be exportable. */ @Required - @CollectionMax(1) - public List getLifetimeAction() { - if (lifetimeAction == null) { - lifetimeAction = new ArrayList<>(); - } + public Boolean getExportable() { + return exportable; + } - return lifetimeAction; + public void setExportable(Boolean exportable) { + this.exportable = exportable; } - public void setLifetimeAction(List lifetimeAction) { - this.lifetimeAction = lifetimeAction; + /** + * When set to ``true`` allows the certificate key to be reused or renewed. + */ + @Required + public Boolean getKeyReusable() { + return keyReusable; + } + + public void setKeyReusable(Boolean keyReusable) { + this.keyReusable = keyReusable; } /** - * Secrets config for the certificate policy. - * - * @subresource gyro.azure.keyvault.KeyVaultCertificateSecretProperties + * Validation of the certificate in months. Value should be between 1 to 12. */ @Required - public KeyVaultCertificateSecretProperties getSecretProperties() { - return secretProperties; + @Range(min = 1, max = 12) + public Integer getValidityInMonths() { + return validityInMonths; + } + + public void setValidityInMonths(Integer validityInMonths) { + this.validityInMonths = validityInMonths; + } + + /** + * The key size. + */ + @ValidNumbers({2048, 3072, 4096}) + public Integer getKeySize() { + return keySize; + } + + public void setKeySize(Integer keySize) { + this.keySize = keySize; + } + + /** + * The date time value in UTC of when the certificate was created. + */ + @Output + public Date getCreatedOn() { + return createdOn; } - public void setSecretProperties(KeyVaultCertificateSecretProperties secretProperties) { - this.secretProperties = secretProperties; + public void setCreatedOn(Date createdOn) { + this.createdOn = createdOn; } /** - * X509 properties for the certificate policy. + * The date time value in UTC of when the certificate was last updated. + */ + @Output + public Date getUpdatedOn() { + return updatedOn; + } + + public void setUpdatedOn(Date updatedOn) { + this.updatedOn = updatedOn; + } + + /** + * Alternate name config for the certificate. * - * @subresource gyro.azure.keyvault.KeyVaultCertificateX509Properties + * @subresource gyro.azure.keyvault.KeyVaultCertificateSubjectAlternativeName */ - @Required - public KeyVaultCertificateX509Properties getX509Properties() { - return x509Properties; + public KeyVaultCertificateSubjectAlternativeName getSubjectAlternativeName() { + return subjectAlternativeName; } - public void setX509Properties(KeyVaultCertificateX509Properties x509Properties) { - this.x509Properties = x509Properties; + public void setSubjectAlternativeName(KeyVaultCertificateSubjectAlternativeName subjectAlternativeName) { + this.subjectAlternativeName = subjectAlternativeName; } /** - * Additional attributes for the certificate policy. + * A list of key usage flags. + */ + public List getKeyUsage() { + if (keyUsage == null) { + keyUsage = new ArrayList<>(); + } + + return keyUsage; + } + + public void setKeyUsage(List keyUsage) { + this.keyUsage = keyUsage; + } + + public List getEnhancedKeyUsage() { + if (enhancedKeyUsage == null) { + enhancedKeyUsage = new ArrayList<>(); + } + + return enhancedKeyUsage; + } + + public void setEnhancedKeyUsage(List enhancedKeyUsage) { + this.enhancedKeyUsage = enhancedKeyUsage; + } + + /** + * Lifetime config for the certificate policy. * - * @subresource gyro.azure.keyvault.KeyVaultCertificateAttribute + * @subresource gyro.azure.keyvault.KeyVaultCertificateLifetime */ - public KeyVaultCertificateAttribute getAttribute() { - return attribute; + @Required + @CollectionMax(1) + public List getLifetimeAction() { + if (lifetimeAction == null) { + lifetimeAction = new ArrayList<>(); + } + + return lifetimeAction; } - public void setAttribute(KeyVaultCertificateAttribute attribute) { - this.attribute = attribute; + public void setLifetimeAction(List lifetimeAction) { + this.lifetimeAction = lifetimeAction; } @Override public void copyFrom(CertificatePolicy certificatePolicy) { - setIssuerParameter(Optional.ofNullable(certificatePolicy.issuerParameters()) - .map(o -> { - KeyVaultCertificateIssuerParameter issuerParameter = newSubresource(KeyVaultCertificateIssuerParameter.class); - issuerParameter.copyFrom(o); - return issuerParameter; - }).orElse(null)); - setKeyProperties(Optional.ofNullable(certificatePolicy.keyProperties()) + setCertificateType(certificatePolicy.getCertificateType()); + setContentType(certificatePolicy.getContentType().toString()); + setIssuerName(certificatePolicy.getIssuerName()); + setSubject(certificatePolicy.getSubject()); + setKeyType(certificatePolicy.getKeyType().toString()); + setKeyCurveName(certificatePolicy.getKeyCurveName().toString()); + setValidityInMonths(certificatePolicy.getValidityInMonths()); + setKeySize(certificatePolicy.getKeySize()); + setCreatedOn(Date.from(certificatePolicy.getCreatedOn().toInstant())); + setUpdatedOn(Date.from(certificatePolicy.getUpdatedOn().toInstant())); + setEnhancedKeyUsage(certificatePolicy.getEnhancedKeyUsage()); + + setTransparent(certificatePolicy.isCertificateTransparent()); + setEnabled(certificatePolicy.isEnabled()); + setExportable(certificatePolicy.isExportable()); + setKeyReusable(certificatePolicy.isKeyReusable()); + + setKeyUsage(Optional.ofNullable(certificatePolicy.getKeyUsage()) + .map(o -> o.stream().map(ExpandableStringEnum::toString).collect(Collectors.toList())) + .orElse(null)); + + setSubjectAlternativeName(Optional.ofNullable(certificatePolicy.getSubjectAlternativeNames()) .map(o -> { - KeyVaultCertificateKeyProperties keyProperties = newSubresource(KeyVaultCertificateKeyProperties.class); - keyProperties.copyFrom(o); - return keyProperties; + KeyVaultCertificateSubjectAlternativeName subjectAlternativeName + = newSubresource(KeyVaultCertificateSubjectAlternativeName.class); + subjectAlternativeName.copyFrom(o); + return subjectAlternativeName; }).orElse(null)); - setLifetimeAction(Optional.ofNullable(certificatePolicy.lifetimeActions()) + + setLifetimeAction(Optional.ofNullable(certificatePolicy.getLifetimeActions()) .map(o -> o.stream().map(oo -> { KeyVaultCertificateLifetime lifetime = newSubresource(KeyVaultCertificateLifetime.class); lifetime.copyFrom(oo); return lifetime; - }).collect(Collectors.toList())).orElse(null));certificatePolicy.lifetimeActions(); - setX509Properties(Optional.ofNullable(certificatePolicy.x509CertificateProperties()) - .map(o -> { - KeyVaultCertificateX509Properties x509Properties = newSubresource(KeyVaultCertificateX509Properties.class); - x509Properties.copyFrom(o); - return x509Properties; - }).orElse(null)); - setSecretProperties(Optional.ofNullable(certificatePolicy.secretProperties()) - .map( o -> { - KeyVaultCertificateSecretProperties secretProperties = newSubresource( - KeyVaultCertificateSecretProperties.class); - secretProperties.copyFrom(o); - return secretProperties; - }).orElse(null)); - setAttribute(Optional.ofNullable(certificatePolicy.attributes()).map( o -> { - KeyVaultCertificateAttribute certificateAttribute = newSubresource(KeyVaultCertificateAttribute.class); - certificateAttribute.copyFrom(o); - return certificateAttribute; - }).orElse(null)); + }).collect(Collectors.toList())).orElse(null)); } @Override @@ -170,15 +323,28 @@ public String primaryKey() { } CertificatePolicy toCertificatePolicy() { - CertificatePolicy policy = new CertificatePolicy(); - policy = policy.withIssuerParameters(getIssuerParameter().toIssuerParameters()); - policy = policy.withKeyProperties(getKeyProperties().toKeyProperties()); - policy = policy.withLifetimeActions(getLifetimeAction() + CertificatePolicy policy = CertificatePolicy.getDefault(); + policy.setLifetimeActions(getLifetimeAction() .stream().map(KeyVaultCertificateLifetime::toLifetimeAction) - .collect(Collectors.toList())); - policy = policy.withSecretProperties(getSecretProperties().toSecretProperties()); - policy = policy.withX509CertificateProperties(getX509Properties().toX509CertificateProperties()); - policy = policy.withAttributes(getAttribute() != null ? getAttribute().toAttributes() : null); + .toArray(LifetimeAction[]::new)); + + policy.setCertificateType(getCertificateType()); + policy.setCertificateTransparent(getTransparent()); + policy.setContentType(CertificateContentType.fromString(getContentType())); + policy.setKeyCurveName(CertificateKeyCurveName.fromString(getKeyCurveName())); + policy.setKeySize(getKeySize()); + policy.setValidityInMonths(getValidityInMonths()); + policy.setEnabled(getEnabled()); + policy.setEnhancedKeyUsage(getEnhancedKeyUsage()); + policy.setExportable(getExportable()); + policy.setKeyReusable(getKeyReusable()); + policy.setSubjectAlternativeNames(getSubjectAlternativeName().toSubjectAlternativeNames()); + policy.setKeyUsage(getKeyUsage().stream() + .map(CertificateKeyUsage::fromString) + .toArray(CertificateKeyUsage[]::new)); + policy.setKeyType(CertificateKeyType.fromString(getKeyType())); + policy.setSubject(getSubject()); + return policy; } } diff --git a/src/main/java/gyro/azure/keyvault/KeyVaultCertificateResource.java b/src/main/java/gyro/azure/keyvault/KeyVaultCertificateResource.java index 1189f74c..c5892b15 100644 --- a/src/main/java/gyro/azure/keyvault/KeyVaultCertificateResource.java +++ b/src/main/java/gyro/azure/keyvault/KeyVaultCertificateResource.java @@ -16,29 +16,32 @@ package gyro.azure.keyvault; +import java.time.Duration; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.Set; -import java.util.concurrent.TimeUnit; -import com.microsoft.azure.keyvault.models.CertificateBundle; -import com.microsoft.azure.keyvault.models.CertificateOperation; -import com.microsoft.azure.keyvault.requests.CreateCertificateRequest; -import com.microsoft.azure.management.keyvault.Vault; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.util.polling.LongRunningOperationStatus; +import com.azure.core.util.polling.SyncPoller; +import com.azure.security.keyvault.certificates.CertificateClient; +import com.azure.security.keyvault.certificates.CertificateClientBuilder; +import com.azure.security.keyvault.certificates.models.CertificateOperation; +import com.azure.security.keyvault.certificates.models.DeletedCertificate; +import com.azure.security.keyvault.certificates.models.KeyVaultCertificateWithPolicy; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.core.GyroCore; -import gyro.core.GyroException; import gyro.core.GyroUI; import gyro.core.Type; -import gyro.core.Wait; import gyro.core.resource.Id; import gyro.core.resource.Output; import gyro.core.resource.Resource; import gyro.core.resource.Updatable; import gyro.core.scope.State; import gyro.core.validation.Required; +import org.jetbrains.annotations.NotNull; /** * Creates a key vault certificate. @@ -93,18 +96,16 @@ * end */ @Type("key-vault-certificate") -public class KeyVaultCertificateResource extends AzureResource implements Copyable { +public class KeyVaultCertificateResource extends AzureResource implements Copyable { private String name; private KeyVaultResource vault; private KeyVaultCertificatePolicy policy; private String version; private String id; - private String sid; private String secretId; - private String kid; - private String keyId; private Map tags; + private Boolean enabled; /** * The name of the certificate. @@ -169,18 +170,6 @@ public void setId(String id) { this.id = id; } - /** - * The SID of the certificate. - */ - @Output - public String getSid() { - return sid; - } - - public void setSid(String sid) { - this.sid = sid; - } - /** * The secret ID of the certificate. */ @@ -193,30 +182,6 @@ public void setSecretId(String secretId) { this.secretId = secretId; } - /** - * The KID of the certificate. - */ - @Output - public String getKid() { - return kid; - } - - public void setKid(String kid) { - this.kid = kid; - } - - /** - * The key ID of the certificate. - */ - @Output - public String getKeyId() { - return keyId; - } - - public void setKeyId(String keyId) { - this.keyId = keyId; - } - /** * Tags for the certificate. */ @@ -233,19 +198,27 @@ public void setTags(Map tags) { this.tags = tags; } + /** + * Enable or Disable the certificate for use. + */ + public Boolean getEnabled() { + return enabled; + } + + public void setEnabled(Boolean enabled) { + this.enabled = enabled; + } + @Override - public void copyFrom(CertificateBundle certificateBundle) { - setName(certificateBundle.certificateIdentifier().name()); - setVersion(certificateBundle.certificateIdentifier().version()); - setId(certificateBundle.id()); - setVault(findById(KeyVaultResource.class, certificateBundle.certificateIdentifier().vault())); - setSecretId(certificateBundle.secretIdentifier().identifier()); - setSid(certificateBundle.sid()); - setKeyId(certificateBundle.keyIdentifier().identifier()); - setKid(certificateBundle.kid()); - setTags(certificateBundle.tags()); - - setPolicy(Optional.ofNullable(certificateBundle.policy()) + public void copyFrom(KeyVaultCertificateWithPolicy certificate) { + setName(certificate.getName()); + setVersion(certificate.getProperties().getVersion()); + setId(certificate.getId()); + setVault(findById(KeyVaultResource.class, certificate.getProperties().getVaultUrl())); + setSecretId(certificate.getSecretId()); + setTags(certificate.getProperties().getTags()); + + setPolicy(Optional.ofNullable(certificate.getPolicy()) .map(o -> { KeyVaultCertificatePolicy certificatePolicy = newSubresource(KeyVaultCertificatePolicy.class); certificatePolicy.copyFrom(o); @@ -255,50 +228,49 @@ public void copyFrom(CertificateBundle certificateBundle) { @Override public boolean refresh() { - Vault vault = getVault().getOldKeyVault(); - CertificateBundle certificateBundle = vault.client().getCertificate(vault.vaultUri(), getName()); + CertificateClient client = getClient(); + + try { + KeyVaultCertificateWithPolicy certificate = client.getCertificate(getName()); + copyFrom(certificate); + return true; + } catch (ResourceNotFoundException ex) { + // ignore + } - return certificateBundle != null; + return false; } @Override public void create(GyroUI ui, State state) throws Exception { - Vault vault = getVault().getOldKeyVault(); - CreateCertificateRequest.Builder builder = new CreateCertificateRequest.Builder(vault.vaultUri(), getName()); - - builder = builder.withPolicy(getPolicy().toCertificatePolicy()); + CertificateClient client = getClient(); - if (!getTags().isEmpty()) { - builder = builder.withTags(getTags()); - } + SyncPoller policySyncPoller = client.beginCreateCertificate( + getName(), + getPolicy().toCertificatePolicy(), + getEnabled(), + getTags()); - vault.client().createCertificate(builder.build()); + KeyVaultCertificateWithPolicy certificate = null; - if (getPolicy().getIssuerParameter().getName().equals("Unknown")) { - GyroCore.ui().write("\n@|blue Certificate created, but needs to be merged before use. Please use the Azure console to merge the certificate! |@\n\n"); - } else { - Wait.atMost(1, TimeUnit.MINUTES) - .checkEvery(10, TimeUnit.SECONDS) - .until(() -> certificateCreationSuccess(vault)); + try { + policySyncPoller.waitUntil(Duration.ofMinutes(5), LongRunningOperationStatus.SUCCESSFULLY_COMPLETED); + certificate = policySyncPoller.getFinalResult(); + } catch (IllegalArgumentException ex) { + // Do something } - CertificateBundle certificateBundle = vault.client().getCertificate(vault.vaultUri(), getName()); - setVersion(certificateBundle.certificateIdentifier().version()); - setId(certificateBundle.id()); - setSecretId(certificateBundle.secretIdentifier().identifier()); - setSid(certificateBundle.sid()); - setKeyId(certificateBundle.keyIdentifier().identifier()); - setKid(certificateBundle.kid()); - } + if (certificate != null) { + copyFrom(certificate); - private boolean certificateCreationSuccess(Vault vault) { - CertificateOperation operation = vault.client().getCertificateOperation(vault.vaultUri(), getName()); + state.save(); - if (operation.error() != null) { - throw new GyroException(operation.error().message()); + if (getPolicy().getIssuerName().equals("Unknown")) { + GyroCore.ui() + .write( + "\n@|blue Certificate created, but needs to be merged before use. Please use the Azure console to merge the certificate! |@\n\n"); + } } - - return operation.status().equals("completed"); } @Override @@ -309,7 +281,21 @@ public void update( @Override public void delete(GyroUI ui, State state) throws Exception { - Vault vault = getVault().getOldKeyVault(); - vault.client().deleteCertificate(vault.id(), getName()); + CertificateClient client = getClient(); + + SyncPoller syncPoller = client.beginDeleteCertificate(getName()); + try { + syncPoller.waitUntil(Duration.ofMinutes(5), LongRunningOperationStatus.SUCCESSFULLY_COMPLETED); + syncPoller.getFinalResult(); + } catch (IllegalArgumentException ex) { + // Do something + } + } + + private CertificateClient getClient() { + return new CertificateClientBuilder() + .vaultUrl(getVault().getUrl()) + .credential(getTokenCredential()) + .buildClient(); } } diff --git a/src/main/java/gyro/azure/keyvault/KeyVaultCertificateSecretProperties.java b/src/main/java/gyro/azure/keyvault/KeyVaultCertificateSecretProperties.java deleted file mode 100644 index 91584e49..00000000 --- a/src/main/java/gyro/azure/keyvault/KeyVaultCertificateSecretProperties.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2020, Perfect Sense, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package gyro.azure.keyvault; - -import com.microsoft.azure.keyvault.models.SecretProperties; -import gyro.azure.Copyable; -import gyro.core.resource.Diffable; -import gyro.core.validation.Required; -import gyro.core.validation.ValidStrings; - -public class KeyVaultCertificateSecretProperties extends Diffable implements Copyable { - - private String contentType; - - /** - * The type of certificate to generate. - */ - @Required - @ValidStrings({"application/x-pem-file", "application/x-pkcs12"}) - public String getContentType() { - return contentType; - } - - public void setContentType(String contentType) { - this.contentType = contentType; - } - - @Override - public String primaryKey() { - return ""; - } - - SecretProperties toSecretProperties() { - return new SecretProperties().withContentType(getContentType()); - } - - @Override - public void copyFrom(SecretProperties secretProperties) { - setContentType(secretProperties.contentType()); - } -} diff --git a/src/main/java/gyro/azure/keyvault/KeyVaultCertificateSubjectAlternativeName.java b/src/main/java/gyro/azure/keyvault/KeyVaultCertificateSubjectAlternativeName.java index 416f48f4..0d09dd9a 100644 --- a/src/main/java/gyro/azure/keyvault/KeyVaultCertificateSubjectAlternativeName.java +++ b/src/main/java/gyro/azure/keyvault/KeyVaultCertificateSubjectAlternativeName.java @@ -18,7 +18,7 @@ import java.util.List; -import com.microsoft.azure.keyvault.models.SubjectAlternativeNames; +import com.azure.security.keyvault.certificates.models.SubjectAlternativeNames; import gyro.azure.Copyable; import gyro.core.resource.Diffable; import gyro.core.validation.Required; @@ -53,7 +53,7 @@ public void setDnsNames(List dnsNames) { } /** - * A list of UPNS values. + * A list of user principal name values. */ public List getUpns() { return upns; @@ -70,15 +70,15 @@ public String primaryKey() { SubjectAlternativeNames toSubjectAlternativeNames() { return new SubjectAlternativeNames() - .withDnsNames(getDnsNames()) - .withEmails(getEmails()) - .withUpns(getUpns()); + .setDnsNames(getDnsNames()) + .setEmails(getEmails()) + .setUserPrincipalNames(getUpns()); } @Override public void copyFrom(SubjectAlternativeNames subjectAlternativeNames) { - setDnsNames(subjectAlternativeNames.dnsNames()); - setEmails(subjectAlternativeNames.emails()); - setUpns(subjectAlternativeNames.upns()); + setDnsNames(subjectAlternativeNames.getDnsNames()); + setEmails(subjectAlternativeNames.getEmails()); + setUpns(subjectAlternativeNames.getUserPrincipalNames()); } } diff --git a/src/main/java/gyro/azure/keyvault/KeyVaultCertificateX509Properties.java b/src/main/java/gyro/azure/keyvault/KeyVaultCertificateX509Properties.java deleted file mode 100644 index 4cdb1ffe..00000000 --- a/src/main/java/gyro/azure/keyvault/KeyVaultCertificateX509Properties.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright 2020, Perfect Sense, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package gyro.azure.keyvault; - -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; - -import com.microsoft.azure.keyvault.models.KeyUsageType; -import com.microsoft.azure.keyvault.models.X509CertificateProperties; -import gyro.azure.Copyable; -import gyro.core.resource.Diffable; -import gyro.core.validation.Range; -import gyro.core.validation.Required; - -public class KeyVaultCertificateX509Properties extends Diffable implements Copyable { - - private List keyUsage; - private String subject; - private KeyVaultCertificateSubjectAlternativeName subjectAlternativeName; - private Integer validityInMonths; - private List ekus; - - /** - * A list of key usage flags. - */ - public List getKeyUsage() { - return keyUsage; - } - - public void setKeyUsage(List keyUsage) { - this.keyUsage = keyUsage; - } - - /** - * The x.500 distinguished name. - */ - @Required - public String getSubject() { - return subject; - } - - public void setSubject(String subject) { - this.subject = subject; - } - - /** - * Alternate name config for the certificate. - * - * @subresource gyro.azure.keyvault.KeyVaultCertificateSubjectAlternativeName - */ - public KeyVaultCertificateSubjectAlternativeName getSubjectAlternativeName() { - return subjectAlternativeName; - } - - public void setSubjectAlternativeName(KeyVaultCertificateSubjectAlternativeName subjectAlternativeName) { - this.subjectAlternativeName = subjectAlternativeName; - } - - /** - * Validation of the certificate in months. Value should be between 1 to 12. - */ - @Required - @Range(min = 1, max = 12) - public Integer getValidityInMonths() { - return validityInMonths; - } - - public void setValidityInMonths(Integer validityInMonths) { - this.validityInMonths = validityInMonths; - } - - /** - * A list of x.660 OID. - */ - public List getEkus() { - return ekus; - } - - public void setEkus(List ekus) { - this.ekus = ekus; - } - - @Override - public String primaryKey() { - return ""; - } - - X509CertificateProperties toX509CertificateProperties() { - return new X509CertificateProperties() - .withEkus(getEkus()) - .withKeyUsage(getKeyUsage().stream().map(KeyUsageType::new).collect(Collectors.toList())) - .withSubject(getSubject()) - .withSubjectAlternativeNames(getSubjectAlternativeName() != null ? getSubjectAlternativeName().toSubjectAlternativeNames() : null) - .withValidityInMonths(getValidityInMonths()); - } - - @Override - public void copyFrom(X509CertificateProperties x509CertificateProperties) { - setEkus(x509CertificateProperties.ekus()); - setSubject(x509CertificateProperties.subject()); - setValidityInMonths(x509CertificateProperties.validityInMonths()); - setKeyUsage(Optional.ofNullable(x509CertificateProperties.keyUsage()) - .map(o -> o.stream().map(KeyUsageType::toString).collect(Collectors.toList())).orElse(null)); - setSubjectAlternativeName(Optional.ofNullable(x509CertificateProperties.subjectAlternativeNames()) - .map(o -> { - KeyVaultCertificateSubjectAlternativeName subjectAlternativeName = newSubresource( - KeyVaultCertificateSubjectAlternativeName.class); - subjectAlternativeName.copyFrom(o); - return subjectAlternativeName; - }).orElse(null)); - } -} diff --git a/src/main/java/gyro/azure/keyvault/KeyVaultKeyFinder.java b/src/main/java/gyro/azure/keyvault/KeyVaultKeyFinder.java index f6c831ee..80f2625d 100644 --- a/src/main/java/gyro/azure/keyvault/KeyVaultKeyFinder.java +++ b/src/main/java/gyro/azure/keyvault/KeyVaultKeyFinder.java @@ -4,10 +4,10 @@ import java.util.List; import java.util.Map; -import com.microsoft.azure.keyvault.models.KeyBundle; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.keyvault.Vault; -import gyro.azure.AzureFinder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.keyvault.models.Key; +import com.azure.resourcemanager.keyvault.models.Vault; +import gyro.azure.AzureResourceManagerFinder; import gyro.core.Type; /** @@ -21,7 +21,7 @@ * certificate: $(external-query azure::key-vault-key {resource-group: "resource-group-example", vault: "vault-example", name: "key-example"}) */ @Type("key-vault-key") -public class KeyVaultKeyFinder extends AzureFinder { +public class KeyVaultKeyFinder extends AzureResourceManagerFinder { private String resourceGroup; private String vault; @@ -60,17 +60,18 @@ public void setName(String name) { this.name = name; } @Override - protected List findAllAzure(Azure client) { + protected List findAllAzure(AzureResourceManager client) { throw new UnsupportedOperationException("Finding all keys without any filter is not supported!!"); } @Override - protected List findAzure(Azure client, Map filters) { - List keyBundles = new ArrayList<>(); + protected List findAzure(AzureResourceManager client, Map filters) { + List keys = new ArrayList<>(); Vault vault = client.vaults().getByResourceGroup(filters.get("resource-group"), filters.get("vault")); if (vault != null) { - keyBundles.add(vault.client().getKey(vault.vaultUri(), filters.get("name"))); + keys.add(vault.keys().getByName(filters.get("name"))); } - return keyBundles; + + return keys; } } diff --git a/src/main/java/gyro/azure/keyvault/KeyVaultResource.java b/src/main/java/gyro/azure/keyvault/KeyVaultResource.java index deee04de..f7193baf 100644 --- a/src/main/java/gyro/azure/keyvault/KeyVaultResource.java +++ b/src/main/java/gyro/azure/keyvault/KeyVaultResource.java @@ -25,7 +25,6 @@ import com.azure.core.management.Region; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.keyvault.models.Vault; -import com.microsoft.azure.management.Azure; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.azure.resources.ResourceGroupResource; @@ -521,10 +520,4 @@ Vault getKeyVault() { return client.vaults().getByResourceGroup(getResourceGroup().getName(), getName()); } - - com.microsoft.azure.management.keyvault.Vault getOldKeyVault() { - Azure client = createClient(); - - return client.vaults().getById(getId()); - } } diff --git a/src/main/java/gyro/azure/keyvault/KeyVaultSecretFinder.java b/src/main/java/gyro/azure/keyvault/KeyVaultSecretFinder.java index 8a951d23..e14f017a 100644 --- a/src/main/java/gyro/azure/keyvault/KeyVaultSecretFinder.java +++ b/src/main/java/gyro/azure/keyvault/KeyVaultSecretFinder.java @@ -20,11 +20,10 @@ import java.util.List; import java.util.Map; -import com.microsoft.azure.keyvault.models.CertificateBundle; -import com.microsoft.azure.keyvault.models.SecretBundle; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.keyvault.Vault; -import gyro.azure.AzureFinder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.keyvault.models.Secret; +import com.azure.resourcemanager.keyvault.models.Vault; +import gyro.azure.AzureResourceManagerFinder; import gyro.core.Type; /** @@ -38,7 +37,7 @@ * certificate: $(external-query azure::key-vault-secret {resource-group: "resource-group-example", vault: "vault-example", name: "secret-example"}) */ @Type("key-vault-secret") -public class KeyVaultSecretFinder extends AzureFinder { +public class KeyVaultSecretFinder extends AzureResourceManagerFinder { private String resourceGroup; private String vault; @@ -78,17 +77,18 @@ public void setName(String name) { } @Override - protected List findAllAzure(Azure client) { + protected List findAllAzure(AzureResourceManager client) { throw new UnsupportedOperationException("Finding all secret without any filter is not supported!!"); } @Override - protected List findAzure(Azure client, Map filters) { - List secretBundles = new ArrayList<>(); + protected List findAzure(AzureResourceManager client, Map filters) { + List secrets = new ArrayList<>(); Vault vault = client.vaults().getByResourceGroup(filters.get("resource-group"), filters.get("vault")); if (vault != null) { - secretBundles.add(vault.client().getSecret(vault.vaultUri(), filters.get("name"))); + secrets.add(vault.secrets().getByName(filters.get("name"))); } - return secretBundles; + + return secrets; } } diff --git a/src/main/java/gyro/azure/keyvault/ListVaultCertificateCommand.java b/src/main/java/gyro/azure/keyvault/ListVaultCertificateCommand.java index 78acee39..6c2cfe87 100644 --- a/src/main/java/gyro/azure/keyvault/ListVaultCertificateCommand.java +++ b/src/main/java/gyro/azure/keyvault/ListVaultCertificateCommand.java @@ -17,10 +17,14 @@ package gyro.azure.keyvault; import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; -import com.microsoft.azure.PagedList; -import com.microsoft.azure.keyvault.models.CertificateItem; -import com.microsoft.azure.management.keyvault.Vault; +import com.azure.core.http.rest.PagedIterable; +import com.azure.resourcemanager.keyvault.models.Vault; +import com.azure.security.keyvault.certificates.CertificateClient; +import com.azure.security.keyvault.certificates.CertificateClientBuilder; +import com.azure.security.keyvault.certificates.models.CertificateProperties; +import com.azure.security.keyvault.certificates.models.KeyVaultCertificateWithPolicy; import gyro.core.GyroCore; import gyro.core.GyroException; import picocli.CommandLine.Command; @@ -48,25 +52,33 @@ public void execute() throws Exception { Vault vault = getVault(vaultResourceName); - PagedList certificateItemPagedList = vault.client().listCertificates(vault.vaultUri()); - if (!certificateItemPagedList.isEmpty()) { - certificateItemPagedList.loadAll(); + CertificateClient client = new CertificateClientBuilder() + .vaultUrl(vault.vaultUri()) + .credential(getTokenCredential()) + .buildClient(); - for (CertificateItem certificate : certificateItemPagedList) { - StringBuilder sb = new StringBuilder(); - sb.append("\n***********************"); - sb.append(String.format("\nName: %s", certificate.identifier().name())); - sb.append(String.format("\nVersion: %s", certificate.identifier().version())); + PagedIterable certificateProperties = client.listPropertiesOfCertificates(); - if (showThumbprint) { - sb.append(String.format( - "\nThumbprint: %s", - certificate.x509Thumbprint() != null ? new String(certificate.x509Thumbprint()) : null)); - } + AtomicBoolean found = new AtomicBoolean(false); + certificateProperties.forEach(certProp -> { + found.set(true); + KeyVaultCertificateWithPolicy certificate = client.getCertificate(certProp.getName()); - GyroCore.ui().write(sb.toString()); + StringBuilder sb = new StringBuilder(); + sb.append("\n***********************"); + sb.append(String.format("\nName: %s", certificate.getName())); + sb.append(String.format("\nVersion: %s", certificate.getProperties().getVersion())); + + if (showThumbprint) { + sb.append(String.format( + "\nThumbprint: %s", + certificate.getProperties().getX509Thumbprint() != null ? new String(certificate.getProperties().getX509Thumbprint()) : null)); } - } else { + + GyroCore.ui().write(sb.toString()); + }); + + if (!found.get()) { GyroCore.ui().write("No certificates found!"); } diff --git a/src/main/java/gyro/azure/keyvault/ListVaultSecretCommand.java b/src/main/java/gyro/azure/keyvault/ListVaultSecretCommand.java index ca9c7747..76621c10 100644 --- a/src/main/java/gyro/azure/keyvault/ListVaultSecretCommand.java +++ b/src/main/java/gyro/azure/keyvault/ListVaultSecretCommand.java @@ -1,10 +1,9 @@ package gyro.azure.keyvault; import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; -import com.microsoft.azure.PagedList; -import com.microsoft.azure.keyvault.models.SecretItem; -import com.microsoft.azure.management.keyvault.Vault; +import com.azure.resourcemanager.keyvault.models.Vault; import gyro.core.GyroCore; import gyro.core.GyroException; import picocli.CommandLine.Command; @@ -28,20 +27,18 @@ public void execute() throws Exception { Vault vault = getVault(vaultResourceName); - PagedList secretItemPagedList = vault.client().listSecrets(vault.vaultUri()); - if (!secretItemPagedList.isEmpty()) { - secretItemPagedList.loadAll(); + AtomicBoolean found = new AtomicBoolean(false); + vault.secrets().list().forEach(secret -> { + StringBuilder sb = new StringBuilder(); + sb.append("\n***********************"); + sb.append(String.format("\nName: %s", secret.name())); + sb.append(String.format("\nContent Type: %s", secret.contentType())); - for (SecretItem secret : secretItemPagedList) { - StringBuilder sb = new StringBuilder(); - sb.append("\n***********************"); - sb.append(String.format("\nName: %s", secret.identifier().name())); - sb.append(String.format("\nVersion: %s", secret.identifier().version())); - sb.append(String.format("\nContent Type: %s", secret.contentType())); + GyroCore.ui().write(sb.toString()); + found.set(true); + }); - GyroCore.ui().write(sb.toString()); - } - } else { + if (!found.get()) { GyroCore.ui().write("No secrets found!"); } diff --git a/src/main/java/gyro/azure/keyvault/RemoveVaultCertificateCommand.java b/src/main/java/gyro/azure/keyvault/RemoveVaultCertificateCommand.java index 70cde37f..32385816 100644 --- a/src/main/java/gyro/azure/keyvault/RemoveVaultCertificateCommand.java +++ b/src/main/java/gyro/azure/keyvault/RemoveVaultCertificateCommand.java @@ -16,9 +16,15 @@ package gyro.azure.keyvault; +import java.time.Duration; import java.util.List; -import com.microsoft.azure.management.keyvault.Vault; +import com.azure.core.util.polling.LongRunningOperationStatus; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.keyvault.models.Vault; +import com.azure.security.keyvault.certificates.CertificateClient; +import com.azure.security.keyvault.certificates.CertificateClientBuilder; +import com.azure.security.keyvault.certificates.models.DeletedCertificate; import gyro.core.GyroCore; import gyro.core.GyroException; import picocli.CommandLine.Command; @@ -43,7 +49,20 @@ public void execute() throws Exception { Vault vault = getVault(vaultResourceName); - vault.client().deleteCertificate(vault.vaultUri(), certificateName); + CertificateClient client = new CertificateClientBuilder() + .vaultUrl(vault.vaultUri()) + .credential(getTokenCredential()) + .buildClient(); + + SyncPoller syncPoller = client.beginDeleteCertificate( + certificateName); + try { + syncPoller.waitUntil(Duration.ofMinutes(5), LongRunningOperationStatus.SUCCESSFULLY_COMPLETED); + syncPoller.getFinalResult(); + } catch (IllegalArgumentException ex) { + // Do something + } + GyroCore.ui().write("\nCertificate removed."); } else { diff --git a/src/main/java/gyro/azure/keyvault/RemoveVaultSecretCommand.java b/src/main/java/gyro/azure/keyvault/RemoveVaultSecretCommand.java index 50392adb..de3555bb 100644 --- a/src/main/java/gyro/azure/keyvault/RemoveVaultSecretCommand.java +++ b/src/main/java/gyro/azure/keyvault/RemoveVaultSecretCommand.java @@ -2,7 +2,8 @@ import java.util.List; -import com.microsoft.azure.management.keyvault.Vault; +import com.azure.resourcemanager.keyvault.models.Secret; +import com.azure.resourcemanager.keyvault.models.Vault; import gyro.core.GyroCore; import gyro.core.GyroException; import picocli.CommandLine.Command; @@ -27,7 +28,8 @@ public void execute() throws Exception { Vault vault = getVault(vaultResourceName); - vault.client().deleteSecret(vault.vaultUri(), secretName); + Secret secret = vault.secrets().getByName(secretName); + vault.secrets().deleteById(secret.id()); GyroCore.ui().write("\nSecret removed."); } else { diff --git a/src/main/java/gyro/azure/network/AbstractApplicationGatewayCommand.java b/src/main/java/gyro/azure/network/AbstractApplicationGatewayCommand.java index 79cd8803..0562fc17 100644 --- a/src/main/java/gyro/azure/network/AbstractApplicationGatewayCommand.java +++ b/src/main/java/gyro/azure/network/AbstractApplicationGatewayCommand.java @@ -3,8 +3,7 @@ import java.util.concurrent.Callable; import com.azure.resourcemanager.AzureResourceManager; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.network.ApplicationGateway; +import com.azure.resourcemanager.network.models.ApplicationGateway; import gyro.azure.AbstractAzureCommand; import gyro.core.GyroException; import gyro.core.command.GyroCommand; @@ -19,33 +18,10 @@ ApplicationGateway getApplicationGateway(String applicationGatewayResourceName) Resource resource = scope.findResource("azure::application-gateway::" + applicationGatewayResourceName); - if (resource instanceof ApplicationGatewayResource) { - Azure client = getClient(); - - ApplicationGateway applicationGateway = client.applicationGateways() - .getById(((ApplicationGatewayResource) resource).getId()); - - if (applicationGateway == null) { - throw new GyroException("The application gateway no longer exists!!"); - } - - return applicationGateway; - } else { - throw new GyroException(String.format( - "No 'application-gateway' resource found with name - %s", - applicationGatewayResourceName)); - } - } - - com.azure.resourcemanager.network.models.ApplicationGateway getApplicationGatewayResourceManager(String applicationGatewayResourceName) { - RootScope scope = getScope(); - - Resource resource = scope.findResource("azure::application-gateway::" + applicationGatewayResourceName); - if (resource instanceof ApplicationGatewayResource) { AzureResourceManager client = getResourceManagerClient(); - com.azure.resourcemanager.network.models.ApplicationGateway applicationGateway = client.applicationGateways() + ApplicationGateway applicationGateway = client.applicationGateways() .getById(((ApplicationGatewayResource) resource).getId()); if (applicationGateway == null) { diff --git a/src/main/java/gyro/azure/network/AddApplicationGatewayCertificateCommand.java b/src/main/java/gyro/azure/network/AddApplicationGatewayCertificateCommand.java index 60af9c08..397b5e37 100644 --- a/src/main/java/gyro/azure/network/AddApplicationGatewayCertificateCommand.java +++ b/src/main/java/gyro/azure/network/AddApplicationGatewayCertificateCommand.java @@ -32,7 +32,7 @@ public void execute() throws Exception { String certificateName = arguments.get(1); String certificatePath = arguments.get(2); - ApplicationGateway applicationGateway = getApplicationGatewayResourceManager(applicationGatewayResourceName); + ApplicationGateway applicationGateway = getApplicationGateway(applicationGatewayResourceName); applicationGateway.update().defineSslCertificate(certificateName) .withPfxFromFile(new File(certificatePath)) diff --git a/src/main/java/gyro/azure/network/ImportApplicationGatewayCertificateCommand.java b/src/main/java/gyro/azure/network/ImportApplicationGatewayCertificateCommand.java index e7bc23ea..af5dcd0b 100644 --- a/src/main/java/gyro/azure/network/ImportApplicationGatewayCertificateCommand.java +++ b/src/main/java/gyro/azure/network/ImportApplicationGatewayCertificateCommand.java @@ -2,9 +2,11 @@ import java.util.List; -import com.microsoft.azure.keyvault.models.CertificateBundle; -import com.microsoft.azure.management.keyvault.Vault; -import com.microsoft.azure.management.network.ApplicationGateway; +import com.azure.resourcemanager.keyvault.models.Vault; +import com.azure.resourcemanager.network.models.ApplicationGateway; +import com.azure.security.keyvault.certificates.CertificateClient; +import com.azure.security.keyvault.certificates.CertificateClientBuilder; +import com.azure.security.keyvault.certificates.models.KeyVaultCertificateWithPolicy; import gyro.azure.keyvault.AbstractVaultCommand; import gyro.core.GyroCore; import gyro.core.GyroException; @@ -32,13 +34,19 @@ public void execute() throws Exception { ApplicationGateway applicationGateway = getApplicationGateway(applicationGatewayResourceName); - Vault vault = AbstractVaultCommand.getVault(vaultResourceName, getScope(), getClient()); + Vault vault = AbstractVaultCommand.getVault(vaultResourceName, getScope(), getResourceManagerClient()); + + CertificateClient client = new CertificateClientBuilder() + .vaultUrl(vault.vaultUri()) + .credential(null) + .buildClient(); + + KeyVaultCertificateWithPolicy certificate = client.getCertificate(vaultCertificateName); - CertificateBundle certificate = vault.client().getCertificate(vault.vaultUri(), vaultCertificateName); applicationGateway.update() .defineSslCertificate(certificateName) - .withKeyVaultSecretId(certificate.sid()) + .withKeyVaultSecretId(certificate.getSecretId()) .attach() .apply(); diff --git a/src/main/java/gyro/azure/network/ListApplicationGatewayCertificateCommand.java b/src/main/java/gyro/azure/network/ListApplicationGatewayCertificateCommand.java index 9c4ddfcf..adb4c562 100644 --- a/src/main/java/gyro/azure/network/ListApplicationGatewayCertificateCommand.java +++ b/src/main/java/gyro/azure/network/ListApplicationGatewayCertificateCommand.java @@ -49,7 +49,7 @@ public void execute() throws Exception { if (arguments.size() == 1) { String applicationGatewayResourceName = arguments.get(0); - ApplicationGateway applicationGateway = getApplicationGatewayResourceManager(applicationGatewayResourceName); + ApplicationGateway applicationGateway = getApplicationGateway(applicationGatewayResourceName); List sslCertificates = new ArrayList<>(applicationGateway.sslCertificates() .values()); diff --git a/src/main/java/gyro/azure/network/RemoveApplicationGatewayCertificateCommand.java b/src/main/java/gyro/azure/network/RemoveApplicationGatewayCertificateCommand.java index a6b37f0f..b5f65c25 100644 --- a/src/main/java/gyro/azure/network/RemoveApplicationGatewayCertificateCommand.java +++ b/src/main/java/gyro/azure/network/RemoveApplicationGatewayCertificateCommand.java @@ -26,7 +26,7 @@ public void execute() throws Exception { String applicationGatewayResourceName = arguments.get(0); String certificateName = arguments.get(1); - ApplicationGateway applicationGateway = getApplicationGatewayResourceManager(applicationGatewayResourceName); + ApplicationGateway applicationGateway = getApplicationGateway(applicationGatewayResourceName); ApplicationGatewayListener listener = applicationGateway.listeners() .values() From 79ff36d13791827013e3d1bb4a6412c9c0f293f3 Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Fri, 3 Jun 2022 19:05:00 -0400 Subject: [PATCH 37/43] complete refactor out old client --- .../java/gyro/azure/AbstractAzureCommand.java | 2 +- .../java/gyro/azure/AzureCredentials.java | 96 ++++++------------- src/main/java/gyro/azure/AzureFinder.java | 21 ++-- src/main/java/gyro/azure/AzureResource.java | 23 +++-- .../azure/AzureResourceManagerFinder.java | 76 --------------- .../ActiveDirectoryGroupFinder.java | 4 +- .../ActiveDirectoryGroupResource.java | 6 +- .../ActiveDirectoryUserFinder.java | 4 +- .../ActiveDirectoryUserResource.java | 6 +- .../accessmanagement/ApplicationFinder.java | 4 +- .../accessmanagement/ApplicationResource.java | 8 +- .../RoleAssignmentResource.java | 8 +- .../ServicePrincipalFinder.java | 4 +- .../ServicePrincipalResource.java | 6 +- .../gyro/azure/cdn/CdnEndpointResource.java | 6 +- .../java/gyro/azure/cdn/CdnProfileFinder.java | 4 +- .../gyro/azure/cdn/CdnProfileResource.java | 8 +- .../azure/compute/AvailabilitySetFinder.java | 4 +- .../compute/AvailabilitySetResource.java | 8 +- .../java/gyro/azure/compute/DiskFinder.java | 4 +- .../java/gyro/azure/compute/DiskResource.java | 8 +- .../gyro/azure/compute/SnapshotFinder.java | 4 +- .../gyro/azure/compute/SnapshotResource.java | 8 +- .../gyro/azure/compute/VMScaleSetFinder.java | 4 +- .../azure/compute/VMScaleSetResource.java | 10 +- .../compute/VMScaleSetScalingFinder.java | 4 +- .../compute/VMScaleSetScalingResource.java | 8 +- .../azure/compute/VirtualMachineFinder.java | 4 +- .../compute/VirtualMachineImageFinder.java | 4 +- .../compute/VirtualMachineImageResource.java | 6 +- .../azure/compute/VirtualMachineResource.java | 10 +- .../KubernetesClusterFinder.java | 4 +- .../KubernetesClusterResource.java | 12 +-- .../azure/cosmosdb/CosmosDBAccountFinder.java | 4 +- .../cosmosdb/CosmosDBAccountResource.java | 8 +- .../java/gyro/azure/dns/ARecordSetFinder.java | 4 +- .../gyro/azure/dns/ARecordSetResource.java | 8 +- .../gyro/azure/dns/AaaaRecordSetFinder.java | 4 +- .../gyro/azure/dns/AaaaRecordSetResource.java | 8 +- .../gyro/azure/dns/CaaRecordSetFinder.java | 4 +- .../gyro/azure/dns/CaaRecordSetResource.java | 8 +- .../gyro/azure/dns/CnameRecordSetFinder.java | 4 +- .../azure/dns/CnameRecordSetResource.java | 8 +- .../java/gyro/azure/dns/DnsZoneFinder.java | 4 +- .../java/gyro/azure/dns/DnsZoneResource.java | 8 +- .../gyro/azure/dns/MxRecordSetFinder.java | 4 +- .../gyro/azure/dns/MxRecordSetResource.java | 8 +- .../gyro/azure/dns/PtrRecordSetFinder.java | 4 +- .../gyro/azure/dns/PtrRecordSetResource.java | 8 +- .../gyro/azure/dns/SrvRecordSetFinder.java | 4 +- .../gyro/azure/dns/SrvRecordSetResource.java | 8 +- .../gyro/azure/dns/TxtRecordSetFinder.java | 4 +- .../gyro/azure/dns/TxtRecordSetResource.java | 8 +- .../gyro/azure/identity/IdentityFinder.java | 4 +- .../gyro/azure/identity/IdentityResource.java | 8 +- .../keyvault/KeyVaultCertificateFinder.java | 4 +- .../gyro/azure/keyvault/KeyVaultFinder.java | 4 +- .../azure/keyvault/KeyVaultKeyFinder.java | 4 +- .../gyro/azure/keyvault/KeyVaultResource.java | 10 +- .../azure/keyvault/KeyVaultSecretFinder.java | 4 +- .../network/ApplicationGatewayFinder.java | 4 +- .../network/ApplicationGatewayResource.java | 10 +- .../ApplicationSecurityGroupFinder.java | 4 +- .../ApplicationSecurityGroupResource.java | 8 +- .../azure/network/LoadBalancerFinder.java | 4 +- .../azure/network/LoadBalancerResource.java | 8 +- .../gyro/azure/network/NetworkFinder.java | 4 +- .../azure/network/NetworkInterfaceFinder.java | 4 +- .../network/NetworkInterfaceResource.java | 8 +- .../gyro/azure/network/NetworkResource.java | 8 +- .../network/NetworkSecurityGroupFinder.java | 4 +- .../network/NetworkSecurityGroupResource.java | 8 +- .../NetworkSecurityGroupRuleResource.java | 6 +- .../network/NicIpConfigurationResource.java | 6 +- .../azure/network/PublicIpAddressFinder.java | 4 +- .../network/PublicIpAddressResource.java | 8 +- .../gyro/azure/network/RouteTableFinder.java | 4 +- .../azure/network/RouteTableResource.java | 8 +- .../gyro/azure/network/SubnetResource.java | 6 +- .../gyro/azure/registries/RegistryFinder.java | 4 +- .../azure/registries/RegistryResource.java | 8 +- .../azure/resources/ResourceGroupFinder.java | 4 +- .../resources/ResourceGroupResource.java | 8 +- .../gyro/azure/sql/SqlDatabaseFinder.java | 4 +- .../gyro/azure/sql/SqlDatabaseResource.java | 8 +- .../gyro/azure/sql/SqlElasticPoolFinder.java | 4 +- .../azure/sql/SqlElasticPoolResource.java | 8 +- .../azure/sql/SqlFailoverGroupFinder.java | 4 +- .../azure/sql/SqlFailoverGroupResource.java | 8 +- .../gyro/azure/sql/SqlFirewallRuleFinder.java | 4 +- .../azure/sql/SqlFirewallRuleResource.java | 8 +- .../java/gyro/azure/sql/SqlServerFinder.java | 4 +- .../gyro/azure/sql/SqlServerResource.java | 8 +- .../sql/SqlVirtualNetworkRuleFinder.java | 4 +- .../sql/SqlVirtualNetworkRuleResource.java | 8 +- .../azure/storage/StorageAccountFinder.java | 4 +- .../azure/storage/StorageAccountResource.java | 12 +-- .../gyro/azure/storage/StorageLifeCycle.java | 6 +- 98 files changed, 332 insertions(+), 448 deletions(-) delete mode 100644 src/main/java/gyro/azure/AzureResourceManagerFinder.java diff --git a/src/main/java/gyro/azure/AbstractAzureCommand.java b/src/main/java/gyro/azure/AbstractAzureCommand.java index 575407eb..7c2a365a 100644 --- a/src/main/java/gyro/azure/AbstractAzureCommand.java +++ b/src/main/java/gyro/azure/AbstractAzureCommand.java @@ -97,7 +97,7 @@ public AzureResourceManager getResourceManagerClient() { getCredential())); } - return AzureResource.createResourceManagerClient((AzureCredentials) credentials); + return AzureResource.createClient((AzureCredentials) credentials); } public TokenCredential getTokenCredential() { diff --git a/src/main/java/gyro/azure/AzureCredentials.java b/src/main/java/gyro/azure/AzureCredentials.java index 46dd4dfe..d7ff99ae 100644 --- a/src/main/java/gyro/azure/AzureCredentials.java +++ b/src/main/java/gyro/azure/AzureCredentials.java @@ -18,34 +18,17 @@ import java.io.IOException; import java.io.InputStream; -import java.net.InetSocketAddress; -import java.util.Collections; import java.util.Properties; -import com.azure.core.http.HttpClient; -import com.azure.core.http.ProxyOptions; +import com.azure.core.credential.TokenCredential; import com.azure.core.http.okhttp.OkHttpAsyncHttpClientBuilder; import com.azure.core.management.profile.AzureProfile; -import com.azure.identity.ClientSecretCredential; import com.azure.identity.ClientSecretCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; -import com.microsoft.azure.AzureEnvironment; -import com.microsoft.azure.AzureResponseBuilder; -import com.microsoft.azure.credentials.ApplicationTokenCredentials; -import com.microsoft.azure.credentials.AzureTokenCredentials; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.resources.fluentcore.utils.ProviderRegistrationInterceptor; -import com.microsoft.azure.management.resources.fluentcore.utils.ResourceManagerThrottlingInterceptor; -import com.microsoft.azure.serializer.AzureJacksonAdapter; -import com.microsoft.rest.LogLevel; -import com.microsoft.rest.RestClient; import com.psddev.dari.util.ObjectUtils; import com.psddev.dari.util.StringUtils; import gyro.core.GyroException; import gyro.core.auth.Credentials; -import okhttp3.OkHttpClient; -import okhttp3.Protocol; -import retrofit2.Retrofit; public class AzureCredentials extends Credentials { @@ -77,8 +60,7 @@ public void setLogLevel(String logLevel) { this.logLevel = logLevel; } - public Azure createClient() { - AzureEnvironment environment = AzureEnvironment.AZURE; + public AzureResourceManager crateClient() { Properties properties; try (InputStream input = openInput(getCredentialFilePath())) { @@ -89,39 +71,42 @@ public Azure createClient() { } catch (IOException error) { throw new GyroException(error.getMessage()); } + String tenant = ObjectUtils.to(String.class, properties.get("tenant")); - AzureTokenCredentials credentials = new ApplicationTokenCredentials( + TokenCredential credential = getTokenCredential(tenant, ObjectUtils.to(String.class, properties.get("client")), - tenant, - ObjectUtils.to(String.class, properties.get("key")), - environment); - - OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder().protocols(Collections.singletonList(Protocol.HTTP_1_1)); - RestClient restClient = new RestClient.Builder(httpBuilder, new Retrofit.Builder()) - .withBaseUrl(credentials.environment(), AzureEnvironment.Endpoint.RESOURCE_MANAGER) - .withCredentials(credentials) - .withSerializerAdapter(new AzureJacksonAdapter()) - .withResponseBuilderFactory(new AzureResponseBuilder.Factory()) - .withInterceptor(new ProviderRegistrationInterceptor(credentials)) - .withInterceptor(new ResourceManagerThrottlingInterceptor()) - .withLogLevel(LogLevel.valueOf(getLogLevel())) - .build(); + ObjectUtils.to(String.class, properties.get("key"))); + + String subscription = ObjectUtils.to(String.class, properties.get("subscription")); + + AzureProfile azureProfile = new AzureProfile(tenant, subscription, com.azure.core.management.AzureEnvironment.AZURE); try { - Azure.Authenticated authenticate = Azure.authenticate(restClient, tenant); - String subscription = ObjectUtils.to(String.class, properties.get("subscription")); + AzureResourceManager.Authenticated authenticated = AzureResourceManager + .configure() + .withHttpClient(new OkHttpAsyncHttpClientBuilder().build()) + .authenticate(credential, azureProfile); + return StringUtils.isBlank(subscription) - ? authenticate.withDefaultSubscription() - : authenticate.withSubscription(subscription); + ? authenticated.withDefaultSubscription() + : authenticated.withSubscription(subscription); - } catch (IOException error) { + } catch (Exception error) { throw new GyroException(error.getMessage(), error); } } - public AzureResourceManager createResourceManagerClient() { + public TokenCredential getTokenCredential(String tenant, String client, String key) { + return new ClientSecretCredentialBuilder() + .clientId(ObjectUtils.to(String.class, client)) + .clientSecret(ObjectUtils.to(String.class, key)) + .tenantId(tenant) + .build(); + } + + public TokenCredential getTokenCredential() { Properties properties; try (InputStream input = openInput(getCredentialFilePath())) { @@ -133,32 +118,9 @@ public AzureResourceManager createResourceManagerClient() { throw new GyroException(error.getMessage()); } - String tenant = ObjectUtils.to(String.class, properties.get("tenant")); - - ClientSecretCredential credential = new ClientSecretCredentialBuilder() - .clientId(ObjectUtils.to(String.class, properties.get("client"))) - .clientSecret(ObjectUtils.to(String.class, properties.get("key"))) - .tenantId(tenant) - .build(); - - String subscription = ObjectUtils.to(String.class, properties.get("subscription")); - - AzureProfile azureProfile = new AzureProfile(tenant, subscription, com.azure.core.management.AzureEnvironment.AZURE); - - try { - AzureResourceManager.Authenticated authenticated = AzureResourceManager - .configure() - .withHttpClient(new OkHttpAsyncHttpClientBuilder().build()) - .authenticate(credential, azureProfile); - - - return StringUtils.isBlank(subscription) - ? authenticated.withDefaultSubscription() - : authenticated.withSubscription(subscription); - - } catch (Exception error) { - throw new GyroException(error.getMessage(), error); - } + return getTokenCredential(ObjectUtils.to(String.class, properties.get("tenant")), + ObjectUtils.to(String.class, properties.get("client")), + ObjectUtils.to(String.class, properties.get("key"))); } } diff --git a/src/main/java/gyro/azure/AzureFinder.java b/src/main/java/gyro/azure/AzureFinder.java index f484c1ea..17a43b23 100644 --- a/src/main/java/gyro/azure/AzureFinder.java +++ b/src/main/java/gyro/azure/AzureFinder.java @@ -1,5 +1,5 @@ /* - * Copyright 2019, Perfect Sense, Inc. + * Copyright 2022, Brightspot, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,19 +16,19 @@ package gyro.azure; -import com.microsoft.azure.management.Azure; -import gyro.core.finder.Finder; - import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; -public abstract class AzureFinder extends Finder { +import com.azure.core.credential.TokenCredential; +import com.azure.resourcemanager.AzureResourceManager; +import gyro.core.finder.Finder; - protected abstract List findAllAzure(Azure client); +public abstract class AzureFinder extends Finder { + protected abstract List findAllAzure(AzureResourceManager client); - protected abstract List findAzure(Azure client, Map filters); + protected abstract List findAzure(AzureResourceManager client, Map filters); @Override public List find(Map filters) { @@ -44,10 +44,14 @@ public List findAll() { .collect(Collectors.toList()); } - private Azure newClient() { + private AzureResourceManager newClient() { return AzureResource.createClient(credentials(AzureCredentials.class)); } + protected TokenCredential getTokenCredential() { + return AzureResource.getTokenCredential(credentials(AzureCredentials.class)); + } + @SuppressWarnings("unchecked") private R newResource(M model) { R resource = newResource(); @@ -69,5 +73,4 @@ private Map convertFilters(Map query) { return filters; } - } diff --git a/src/main/java/gyro/azure/AzureResource.java b/src/main/java/gyro/azure/AzureResource.java index ecda41da..b2f8e362 100644 --- a/src/main/java/gyro/azure/AzureResource.java +++ b/src/main/java/gyro/azure/AzureResource.java @@ -16,30 +16,29 @@ package gyro.azure; +import com.azure.core.credential.TokenCredential; import com.azure.resourcemanager.AzureResourceManager; import gyro.core.resource.Resource; -import com.microsoft.azure.management.Azure; public abstract class AzureResource extends Resource { - public static Azure createClient(AzureCredentials credentials) { - return credentials.createClient(); + protected String getRegion() { + return credentials(AzureCredentials.class).getRegion(); } - protected Azure createClient() { - return AzureResource.createClient(credentials(AzureCredentials.class)); + public static AzureResourceManager createClient(AzureCredentials credentials) { + return credentials.crateClient(); } - protected String getRegion() { - return credentials(AzureCredentials.class).getRegion(); + protected AzureResourceManager createClient() { + return AzureResource.createClient(credentials(AzureCredentials.class)); } - public static AzureResourceManager createResourceManagerClient(AzureCredentials credentials) { - return credentials.createResourceManagerClient(); + public static TokenCredential getTokenCredential(AzureCredentials credentials) { + return credentials.getTokenCredential(); } - protected AzureResourceManager createResourceManagerClient() { - return AzureResource.createResourceManagerClient(credentials(AzureCredentials.class)); + protected TokenCredential getTokenCredential() { + return credentials(AzureCredentials.class).getTokenCredential(); } - } diff --git a/src/main/java/gyro/azure/AzureResourceManagerFinder.java b/src/main/java/gyro/azure/AzureResourceManagerFinder.java deleted file mode 100644 index 6208756b..00000000 --- a/src/main/java/gyro/azure/AzureResourceManagerFinder.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright 2022, Brightspot, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package gyro.azure; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import com.azure.core.credential.TokenCredential; -import com.azure.resourcemanager.AzureResourceManager; -import gyro.core.finder.Finder; - -public abstract class AzureResourceManagerFinder extends Finder { - protected abstract List findAllAzure(AzureResourceManager client); - - protected abstract List findAzure(AzureResourceManager client, Map filters); - - @Override - public List find(Map filters) { - return findAzure(newClient(), convertFilters(filters)).stream() - .map(this::newResource) - .collect(Collectors.toList()); - } - - @Override - public List findAll() { - return findAllAzure(newClient()).stream() - .map(this::newResource) - .collect(Collectors.toList()); - } - - private AzureResourceManager newClient() { - return AzureResource.createResourceManagerClient(credentials(AzureCredentials.class)); - } - - protected TokenCredential getTokenCredential() { - return AzureResource.getTokenCredential(credentials(AzureCredentials.class)); - } - - @SuppressWarnings("unchecked") - private R newResource(M model) { - R resource = newResource(); - - if (resource instanceof Copyable) { - ((Copyable) resource).copyFrom(model); - } - - return resource; - } - - @SuppressWarnings("unchecked") - private Map convertFilters(Map query) { - Map filters = new HashMap<>(); - - for (Map.Entry e : query.entrySet()) { - filters.put(e.getKey(), e.getValue().toString()); - } - - return filters; - } -} diff --git a/src/main/java/gyro/azure/accessmanagement/ActiveDirectoryGroupFinder.java b/src/main/java/gyro/azure/accessmanagement/ActiveDirectoryGroupFinder.java index 9b0bb990..d6755a45 100644 --- a/src/main/java/gyro/azure/accessmanagement/ActiveDirectoryGroupFinder.java +++ b/src/main/java/gyro/azure/accessmanagement/ActiveDirectoryGroupFinder.java @@ -23,7 +23,7 @@ import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.authorization.models.ActiveDirectoryGroup; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.GyroException; import gyro.core.Type; @@ -39,7 +39,7 @@ */ @Type("active-directory-group") public class ActiveDirectoryGroupFinder - extends AzureResourceManagerFinder { + extends AzureFinder { private String name; private String id; diff --git a/src/main/java/gyro/azure/accessmanagement/ActiveDirectoryGroupResource.java b/src/main/java/gyro/azure/accessmanagement/ActiveDirectoryGroupResource.java index d1aa5b2f..58233f12 100644 --- a/src/main/java/gyro/azure/accessmanagement/ActiveDirectoryGroupResource.java +++ b/src/main/java/gyro/azure/accessmanagement/ActiveDirectoryGroupResource.java @@ -95,7 +95,7 @@ public void copyFrom(ActiveDirectoryGroup group) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); ActiveDirectoryGroup group = client.accessManagement().activeDirectoryGroups().getById(getId()); @@ -110,7 +110,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) throws Exception { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); ActiveDirectoryGroup group = client.accessManagement().activeDirectoryGroups() .define(getName()) @@ -127,7 +127,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) throws Exception { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.accessManagement().activeDirectoryGroups().deleteById(getId()); } diff --git a/src/main/java/gyro/azure/accessmanagement/ActiveDirectoryUserFinder.java b/src/main/java/gyro/azure/accessmanagement/ActiveDirectoryUserFinder.java index 4e027065..b1f05760 100644 --- a/src/main/java/gyro/azure/accessmanagement/ActiveDirectoryUserFinder.java +++ b/src/main/java/gyro/azure/accessmanagement/ActiveDirectoryUserFinder.java @@ -23,7 +23,7 @@ import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.authorization.models.ActiveDirectoryUser; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.GyroException; import gyro.core.Type; @@ -39,7 +39,7 @@ */ @Type("active-directory-user") public class ActiveDirectoryUserFinder - extends AzureResourceManagerFinder { + extends AzureFinder { private String id; private String name; diff --git a/src/main/java/gyro/azure/accessmanagement/ActiveDirectoryUserResource.java b/src/main/java/gyro/azure/accessmanagement/ActiveDirectoryUserResource.java index 6aecd4d5..dadc79d4 100644 --- a/src/main/java/gyro/azure/accessmanagement/ActiveDirectoryUserResource.java +++ b/src/main/java/gyro/azure/accessmanagement/ActiveDirectoryUserResource.java @@ -141,7 +141,7 @@ public void copyFrom(ActiveDirectoryUser user) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); ActiveDirectoryUser user = client.accessManagement().activeDirectoryUsers().getById(getId()); @@ -156,7 +156,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) throws Exception { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); ActiveDirectoryUser activeDirectoryUser = client.accessManagement().activeDirectoryUsers() .define(getName()) @@ -175,7 +175,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) throws Exception { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.accessManagement().activeDirectoryUsers().deleteById(getId()); } diff --git a/src/main/java/gyro/azure/accessmanagement/ApplicationFinder.java b/src/main/java/gyro/azure/accessmanagement/ApplicationFinder.java index 6eef2a05..00da2c25 100644 --- a/src/main/java/gyro/azure/accessmanagement/ApplicationFinder.java +++ b/src/main/java/gyro/azure/accessmanagement/ApplicationFinder.java @@ -23,7 +23,7 @@ import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.authorization.models.ActiveDirectoryApplication; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.Type; /** @@ -37,7 +37,7 @@ * application: $(external-query azure::application {}) */ @Type("application") -public class ApplicationFinder extends AzureResourceManagerFinder { +public class ApplicationFinder extends AzureFinder { private String id; diff --git a/src/main/java/gyro/azure/accessmanagement/ApplicationResource.java b/src/main/java/gyro/azure/accessmanagement/ApplicationResource.java index 8336de38..3476f98c 100644 --- a/src/main/java/gyro/azure/accessmanagement/ApplicationResource.java +++ b/src/main/java/gyro/azure/accessmanagement/ApplicationResource.java @@ -171,7 +171,7 @@ public void copyFrom(ActiveDirectoryApplication model) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); ActiveDirectoryApplication application = client.accessManagement() .activeDirectoryApplications() @@ -188,7 +188,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) throws Exception { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); ActiveDirectoryApplication.DefinitionStages.WithCreate withCreate = client.accessManagement() .activeDirectoryApplications() @@ -215,7 +215,7 @@ public void create(GyroUI ui, State state) throws Exception { @Override public void update( GyroUI ui, State state, Resource current, Set changedFieldNames) throws Exception { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); ActiveDirectoryApplication application = client.accessManagement() .activeDirectoryApplications() @@ -258,7 +258,7 @@ public void update( @Override public void delete(GyroUI ui, State state) throws Exception { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.accessManagement().activeDirectoryApplications().deleteById(getId()); } diff --git a/src/main/java/gyro/azure/accessmanagement/RoleAssignmentResource.java b/src/main/java/gyro/azure/accessmanagement/RoleAssignmentResource.java index ea0bd4c3..01867c79 100644 --- a/src/main/java/gyro/azure/accessmanagement/RoleAssignmentResource.java +++ b/src/main/java/gyro/azure/accessmanagement/RoleAssignmentResource.java @@ -149,7 +149,7 @@ public void copyFrom(RoleAssignment roleAssignment) { setScope(roleAssignment.scope()); setId(roleAssignment.id()); - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); setRole(client.accessManagement().roleDefinitions().getById(roleAssignment.roleDefinitionId()).roleName()); ActiveDirectoryUser user = client.accessManagement().activeDirectoryUsers().getById(getPrincipalId()); @@ -166,7 +166,7 @@ public void copyFrom(RoleAssignment roleAssignment) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); RoleAssignment roleAssignment = client.accessManagement().roleAssignments().getByScope(getScope(), getName()); @@ -181,7 +181,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) throws Exception { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); if (Stream.of(getPrincipalId(), getUser(), getGroup()).filter(Objects::nonNull).count() > 1) { throw new GyroException("Only one of 'principal-id' or 'user' or 'group' is allowed."); @@ -221,7 +221,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) throws Exception { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.accessManagement().roleAssignments().deleteById(getId()); } diff --git a/src/main/java/gyro/azure/accessmanagement/ServicePrincipalFinder.java b/src/main/java/gyro/azure/accessmanagement/ServicePrincipalFinder.java index b261cbe1..aecdcf0e 100644 --- a/src/main/java/gyro/azure/accessmanagement/ServicePrincipalFinder.java +++ b/src/main/java/gyro/azure/accessmanagement/ServicePrincipalFinder.java @@ -23,7 +23,7 @@ import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.authorization.models.ServicePrincipal; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.Type; /** @@ -37,7 +37,7 @@ * service-principal: $(external-query azure::service-principal {}) */ @Type("service-principal") -public class ServicePrincipalFinder extends AzureResourceManagerFinder { +public class ServicePrincipalFinder extends AzureFinder { private String id; diff --git a/src/main/java/gyro/azure/accessmanagement/ServicePrincipalResource.java b/src/main/java/gyro/azure/accessmanagement/ServicePrincipalResource.java index 2a3227f5..941cd166 100644 --- a/src/main/java/gyro/azure/accessmanagement/ServicePrincipalResource.java +++ b/src/main/java/gyro/azure/accessmanagement/ServicePrincipalResource.java @@ -98,7 +98,7 @@ public void copyFrom(ServicePrincipal model) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); ServicePrincipal servicePrincipal = client.accessManagement().servicePrincipals().getByName(getName()); @@ -113,7 +113,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) throws Exception { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); ServicePrincipal servicePrincipal = client.accessManagement().servicePrincipals() .define(getName()) @@ -131,7 +131,7 @@ public void update( @Override public void delete(GyroUI ui, State state) throws Exception { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.accessManagement().servicePrincipals().deleteById(getId()); } diff --git a/src/main/java/gyro/azure/cdn/CdnEndpointResource.java b/src/main/java/gyro/azure/cdn/CdnEndpointResource.java index 296d4bdb..7b7161bc 100644 --- a/src/main/java/gyro/azure/cdn/CdnEndpointResource.java +++ b/src/main/java/gyro/azure/cdn/CdnEndpointResource.java @@ -339,7 +339,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); CdnProfileResource parent = (CdnProfileResource) parent(); @@ -432,7 +432,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); CdnProfileResource parent = (CdnProfileResource) parent(); @@ -524,7 +524,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); CdnProfileResource parent = (CdnProfileResource) parent(); diff --git a/src/main/java/gyro/azure/cdn/CdnProfileFinder.java b/src/main/java/gyro/azure/cdn/CdnProfileFinder.java index 1c6fb2f4..0b045561 100644 --- a/src/main/java/gyro/azure/cdn/CdnProfileFinder.java +++ b/src/main/java/gyro/azure/cdn/CdnProfileFinder.java @@ -23,7 +23,7 @@ import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.cdn.models.CdnProfile; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.Type; /** @@ -37,7 +37,7 @@ * cdn-profile: $(external-query azure::cdn-profile {}) */ @Type("cdn-profile") -public class CdnProfileFinder extends AzureResourceManagerFinder { +public class CdnProfileFinder extends AzureFinder { private String id; diff --git a/src/main/java/gyro/azure/cdn/CdnProfileResource.java b/src/main/java/gyro/azure/cdn/CdnProfileResource.java index 95868498..f908dadb 100644 --- a/src/main/java/gyro/azure/cdn/CdnProfileResource.java +++ b/src/main/java/gyro/azure/cdn/CdnProfileResource.java @@ -165,7 +165,7 @@ public void copyFrom(CdnProfile cdnProfile) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); CdnProfile cdnProfile = client.cdnProfiles().getById(getId()); @@ -180,7 +180,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); CdnProfile.DefinitionStages.WithSku withSku = client.cdnProfiles().define(getName()) .withRegion(Region.fromName(getRegion())) @@ -200,7 +200,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); CdnProfile.Update update = client.cdnProfiles().getById(getId()).update().withTags(getTags()); update.apply(); @@ -208,7 +208,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.cdnProfiles().deleteById(getId()); } diff --git a/src/main/java/gyro/azure/compute/AvailabilitySetFinder.java b/src/main/java/gyro/azure/compute/AvailabilitySetFinder.java index d4320645..08d08c43 100644 --- a/src/main/java/gyro/azure/compute/AvailabilitySetFinder.java +++ b/src/main/java/gyro/azure/compute/AvailabilitySetFinder.java @@ -23,7 +23,7 @@ import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.AvailabilitySet; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.Type; /** @@ -37,7 +37,7 @@ * availability-set: $(external-query azure::availability-set {}) */ @Type("availability-set") -public class AvailabilitySetFinder extends AzureResourceManagerFinder { +public class AvailabilitySetFinder extends AzureFinder { private String id; diff --git a/src/main/java/gyro/azure/compute/AvailabilitySetResource.java b/src/main/java/gyro/azure/compute/AvailabilitySetResource.java index 34ab2e94..c2712418 100644 --- a/src/main/java/gyro/azure/compute/AvailabilitySetResource.java +++ b/src/main/java/gyro/azure/compute/AvailabilitySetResource.java @@ -175,7 +175,7 @@ public void copyFrom(AvailabilitySet availabilitySet) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); AvailabilitySet availabilitySet = client.availabilitySets().getById(getId()); @@ -190,7 +190,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); AvailabilitySet availabilitySet = client.availabilitySets().define(getName()) .withRegion(Region.fromName(getRegion())) @@ -206,7 +206,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); if (changedFieldNames.contains("sku") && AvailabilitySetSkuTypes.fromString(getSku()) .equals(AvailabilitySetSkuTypes.CLASSIC)) { @@ -223,7 +223,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.availabilitySets().deleteById(getId()); } diff --git a/src/main/java/gyro/azure/compute/DiskFinder.java b/src/main/java/gyro/azure/compute/DiskFinder.java index 37d6bea1..aa7aeb92 100644 --- a/src/main/java/gyro/azure/compute/DiskFinder.java +++ b/src/main/java/gyro/azure/compute/DiskFinder.java @@ -23,7 +23,7 @@ import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.Disk; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.Type; /** @@ -37,7 +37,7 @@ * disk: $(external-query azure::disk {}) */ @Type("disk") -public class DiskFinder extends AzureResourceManagerFinder { +public class DiskFinder extends AzureFinder { private String id; diff --git a/src/main/java/gyro/azure/compute/DiskResource.java b/src/main/java/gyro/azure/compute/DiskResource.java index 2ec2e313..c40a4a55 100644 --- a/src/main/java/gyro/azure/compute/DiskResource.java +++ b/src/main/java/gyro/azure/compute/DiskResource.java @@ -221,7 +221,7 @@ public void copyFrom(Disk disk) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); Disk disk = client.disks().getById(getId()); @@ -236,7 +236,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); Disk.DefinitionStages.WithDiskSource diskDefWithoutData = client.disks() .define(getName()) @@ -291,7 +291,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); Disk disk = client.disks().getById(getId()); @@ -318,7 +318,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.disks().deleteById(getId()); } diff --git a/src/main/java/gyro/azure/compute/SnapshotFinder.java b/src/main/java/gyro/azure/compute/SnapshotFinder.java index 359dd49f..bf4c04b0 100644 --- a/src/main/java/gyro/azure/compute/SnapshotFinder.java +++ b/src/main/java/gyro/azure/compute/SnapshotFinder.java @@ -23,7 +23,7 @@ import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.Snapshot; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.Type; /** @@ -37,7 +37,7 @@ * snapshot: $(external-query azure::snapshot {}) */ @Type("snapshot") -public class SnapshotFinder extends AzureResourceManagerFinder { +public class SnapshotFinder extends AzureFinder { private String id; diff --git a/src/main/java/gyro/azure/compute/SnapshotResource.java b/src/main/java/gyro/azure/compute/SnapshotResource.java index ff4a4de9..a301afb3 100644 --- a/src/main/java/gyro/azure/compute/SnapshotResource.java +++ b/src/main/java/gyro/azure/compute/SnapshotResource.java @@ -253,7 +253,7 @@ public void copyFrom(Snapshot snapshot) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); Snapshot snapshot = client.snapshots().getById(getId()); @@ -268,7 +268,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); Snapshot.DefinitionStages.WithSnapshotSource withSnapshotSource = client.snapshots().define(getName()) .withRegion(Region.fromName(getRegion())) @@ -329,7 +329,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.snapshots().getById(getId()) .update() @@ -340,7 +340,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.snapshots().deleteById(getId()); } diff --git a/src/main/java/gyro/azure/compute/VMScaleSetFinder.java b/src/main/java/gyro/azure/compute/VMScaleSetFinder.java index e0e7a4ba..9456e6de 100644 --- a/src/main/java/gyro/azure/compute/VMScaleSetFinder.java +++ b/src/main/java/gyro/azure/compute/VMScaleSetFinder.java @@ -23,7 +23,7 @@ import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.VirtualMachineScaleSet; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.Type; /** @@ -37,7 +37,7 @@ * scale-set: $(external-query azure::scale-set {}) */ @Type("scale-set") -public class VMScaleSetFinder extends AzureResourceManagerFinder { +public class VMScaleSetFinder extends AzureFinder { private String id; diff --git a/src/main/java/gyro/azure/compute/VMScaleSetResource.java b/src/main/java/gyro/azure/compute/VMScaleSetResource.java index 6ae2665b..b52fe556 100644 --- a/src/main/java/gyro/azure/compute/VMScaleSetResource.java +++ b/src/main/java/gyro/azure/compute/VMScaleSetResource.java @@ -858,7 +858,7 @@ public void copyFrom(VirtualMachineScaleSet scaleSet) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); VirtualMachineScaleSet scaleSet = client.virtualMachineScaleSets().getById(getId()); @@ -873,7 +873,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); VirtualMachineScaleSet.DefinitionStages.WithProximityPlacementGroup withProximityPlacementGroup = client.virtualMachineScaleSets() .define(getName()) @@ -1114,7 +1114,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); VirtualMachineScaleSet scaleSet = client.virtualMachineScaleSets().getById(getId()); @@ -1243,7 +1243,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.virtualMachineScaleSets().deleteById(getId()); } @@ -1251,7 +1251,7 @@ public void delete(GyroUI ui, State state) { @Override public List getInstances() { List instances = new ArrayList<>(); - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); VirtualMachineScaleSet virtualMachineScaleSet = client.virtualMachineScaleSets().getById(getId()); diff --git a/src/main/java/gyro/azure/compute/VMScaleSetScalingFinder.java b/src/main/java/gyro/azure/compute/VMScaleSetScalingFinder.java index 1b8564ae..abcc8f73 100644 --- a/src/main/java/gyro/azure/compute/VMScaleSetScalingFinder.java +++ b/src/main/java/gyro/azure/compute/VMScaleSetScalingFinder.java @@ -23,7 +23,7 @@ import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.monitor.models.AutoscaleSetting; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.Type; /** @@ -37,7 +37,7 @@ * scale-set-scaling: $(external-query azure::scale-set-scaling {}) */ @Type("scale-set-scaling") -public class VMScaleSetScalingFinder extends AzureResourceManagerFinder { +public class VMScaleSetScalingFinder extends AzureFinder { private String id; diff --git a/src/main/java/gyro/azure/compute/VMScaleSetScalingResource.java b/src/main/java/gyro/azure/compute/VMScaleSetScalingResource.java index 17a803cc..d2436e00 100644 --- a/src/main/java/gyro/azure/compute/VMScaleSetScalingResource.java +++ b/src/main/java/gyro/azure/compute/VMScaleSetScalingResource.java @@ -314,7 +314,7 @@ public void copyFrom(AutoscaleSetting autoscaleSetting) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); AutoscaleSetting autoscaleSetting = client.autoscaleSettings().getById(getId()); @@ -329,7 +329,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); AutoscaleSetting.DefinitionStages.DefineAutoscaleSettingResourceProfiles basicStage = client.autoscaleSettings() .define(getName()) @@ -420,7 +420,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) throws Exception { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); AutoscaleSetting autoscaleSetting = client.autoscaleSettings().getById(getId()); @@ -515,7 +515,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.autoscaleSettings().deleteById(getId()); } diff --git a/src/main/java/gyro/azure/compute/VirtualMachineFinder.java b/src/main/java/gyro/azure/compute/VirtualMachineFinder.java index 1edf5e92..d64c7e2c 100644 --- a/src/main/java/gyro/azure/compute/VirtualMachineFinder.java +++ b/src/main/java/gyro/azure/compute/VirtualMachineFinder.java @@ -23,7 +23,7 @@ import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.VirtualMachine; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.Type; /** @@ -37,7 +37,7 @@ * virtual-machine: $(external-query azure::virtual-machine {}) */ @Type("virtual-machine") -public class VirtualMachineFinder extends AzureResourceManagerFinder { +public class VirtualMachineFinder extends AzureFinder { private String id; diff --git a/src/main/java/gyro/azure/compute/VirtualMachineImageFinder.java b/src/main/java/gyro/azure/compute/VirtualMachineImageFinder.java index f2c15541..3fbc78e5 100644 --- a/src/main/java/gyro/azure/compute/VirtualMachineImageFinder.java +++ b/src/main/java/gyro/azure/compute/VirtualMachineImageFinder.java @@ -23,7 +23,7 @@ import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.VirtualMachineCustomImage; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.Type; /** @@ -38,7 +38,7 @@ */ @Type("virtual-machine-image") public class VirtualMachineImageFinder - extends AzureResourceManagerFinder { + extends AzureFinder { private String id; diff --git a/src/main/java/gyro/azure/compute/VirtualMachineImageResource.java b/src/main/java/gyro/azure/compute/VirtualMachineImageResource.java index bac03722..6cfd5570 100644 --- a/src/main/java/gyro/azure/compute/VirtualMachineImageResource.java +++ b/src/main/java/gyro/azure/compute/VirtualMachineImageResource.java @@ -170,7 +170,7 @@ public void copyFrom(VirtualMachineCustomImage image) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); VirtualMachineCustomImage image = client.virtualMachineCustomImages().getById(getId()); @@ -185,7 +185,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) throws Exception { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); VirtualMachineCustomImage.DefinitionStages.WithCreate withCreate = client.virtualMachineCustomImages() .define(getName()) @@ -214,7 +214,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) throws Exception { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.virtualMachineCustomImages().deleteById(getId()); } diff --git a/src/main/java/gyro/azure/compute/VirtualMachineResource.java b/src/main/java/gyro/azure/compute/VirtualMachineResource.java index 1c917fbe..5b1bc9a5 100644 --- a/src/main/java/gyro/azure/compute/VirtualMachineResource.java +++ b/src/main/java/gyro/azure/compute/VirtualMachineResource.java @@ -764,13 +764,13 @@ public void copyFrom(VirtualMachine virtualMachine) { .orElse(null); setLaunchDate(instanceViewStatus != null ? Date.from(instanceViewStatus.time().toInstant()) : null); - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); setPrivateIpAddress(client.networkInterfaces().getById(getNetworkInterface().getId()).primaryPrivateIP()); } @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); VirtualMachine virtualMachine = client.virtualMachines().getById(getId()); @@ -785,7 +785,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - VirtualMachine virtualMachine = doVMFluentWorkflow(createResourceManagerClient()).create(); + VirtualMachine virtualMachine = doVMFluentWorkflow(createClient()).create(); setId(virtualMachine.id()); setVmId(virtualMachine.vmId()); copyFrom(virtualMachine); @@ -1231,7 +1231,7 @@ private WithCreate configureUnmanagedDataDisks( @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); VirtualMachine virtualMachine = client.virtualMachines().getById(getId()); @@ -1296,7 +1296,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); VirtualMachine virtualMachine = client.virtualMachines().getById(getId()); client.virtualMachines().deleteById(getId()); diff --git a/src/main/java/gyro/azure/containerservice/KubernetesClusterFinder.java b/src/main/java/gyro/azure/containerservice/KubernetesClusterFinder.java index ed3e75b8..ccbfeb09 100644 --- a/src/main/java/gyro/azure/containerservice/KubernetesClusterFinder.java +++ b/src/main/java/gyro/azure/containerservice/KubernetesClusterFinder.java @@ -23,7 +23,7 @@ import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.containerservice.models.KubernetesCluster; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.Type; /** @@ -37,7 +37,7 @@ * kubernetes-cluster: $(external-query azure::kubernetes-cluster {}) */ @Type("kubernetes-cluster") -public class KubernetesClusterFinder extends AzureResourceManagerFinder { +public class KubernetesClusterFinder extends AzureFinder { private String id; diff --git a/src/main/java/gyro/azure/containerservice/KubernetesClusterResource.java b/src/main/java/gyro/azure/containerservice/KubernetesClusterResource.java index a25da395..11ff1b1d 100644 --- a/src/main/java/gyro/azure/containerservice/KubernetesClusterResource.java +++ b/src/main/java/gyro/azure/containerservice/KubernetesClusterResource.java @@ -34,14 +34,10 @@ import com.azure.resourcemanager.containerservice.models.KubernetesClusters; import com.azure.resourcemanager.containerservice.models.LoadBalancerSku; import com.azure.resourcemanager.containerservice.models.ManagedClusterAddonProfile; -import com.azure.resourcemanager.containerservice.models.ManagedClusterApiServerAccessProfile; -import com.azure.resourcemanager.containerservice.models.NetworkMode; import com.azure.resourcemanager.containerservice.models.NetworkPlugin; import com.azure.resourcemanager.containerservice.models.NetworkPolicy; import com.azure.resourcemanager.containerservice.models.OSDiskType; import com.azure.resourcemanager.containerservice.models.OSType; -import com.azure.resourcemanager.containerservice.models.OutboundType; -import com.azure.resourcemanager.containerservice.models.PublicNetworkAccess; import com.azure.resourcemanager.containerservice.models.ScaleSetEvictionPolicy; import com.azure.resourcemanager.containerservice.models.ScaleSetPriority; import com.azure.resourcemanager.containerservice.models.KubernetesClusterAgentPool.DefinitionStages.WithAttach; @@ -505,7 +501,7 @@ public void copyFrom(KubernetesCluster cluster) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); KubernetesClusters kubernetesClusters = client.kubernetesClusters(); KubernetesCluster cluster = kubernetesClusters.list().stream() .filter(o -> o.name().equals(getName())) @@ -523,7 +519,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) throws Exception { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); WithServicePrincipalClientId withServicePrincipalClientId = client.kubernetesClusters() .define(getName()) @@ -669,7 +665,7 @@ public void create(GyroUI ui, State state) throws Exception { public void update( GyroUI ui, State state, Resource current, Set changedFieldNames) throws Exception { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); KubernetesCluster cluster = client.kubernetesClusters() .getByResourceGroup(getResourceGroup().getName(), getName()); @@ -800,7 +796,7 @@ public void update( @Override public void delete(GyroUI ui, State state) throws Exception { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.kubernetesClusters().deleteByResourceGroup(getResourceGroup().getName(), getName()); } diff --git a/src/main/java/gyro/azure/cosmosdb/CosmosDBAccountFinder.java b/src/main/java/gyro/azure/cosmosdb/CosmosDBAccountFinder.java index ce519826..09d78a90 100644 --- a/src/main/java/gyro/azure/cosmosdb/CosmosDBAccountFinder.java +++ b/src/main/java/gyro/azure/cosmosdb/CosmosDBAccountFinder.java @@ -18,7 +18,7 @@ import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.cosmos.models.CosmosDBAccount; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.Type; import java.util.Collections; @@ -37,7 +37,7 @@ * cosmos-db: $(external-query azure::cosmos-db {}) */ @Type("cosmos-db") -public class CosmosDBAccountFinder extends AzureResourceManagerFinder { +public class CosmosDBAccountFinder extends AzureFinder { private String id; /** diff --git a/src/main/java/gyro/azure/cosmosdb/CosmosDBAccountResource.java b/src/main/java/gyro/azure/cosmosdb/CosmosDBAccountResource.java index aa0cd213..b99a25dd 100644 --- a/src/main/java/gyro/azure/cosmosdb/CosmosDBAccountResource.java +++ b/src/main/java/gyro/azure/cosmosdb/CosmosDBAccountResource.java @@ -287,7 +287,7 @@ public void copyFrom(CosmosDBAccount cosmosAccount) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); CosmosDBAccount cosmosAccount = client.cosmosDBAccounts().getById(getId()); @@ -302,7 +302,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); WithKind withKind = client.cosmosDBAccounts() .define(getName()) @@ -357,7 +357,7 @@ && getMaxInterval() != null) { @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); CosmosDBAccount.Update update = client.cosmosDBAccounts() .getById(getId()) @@ -417,7 +417,7 @@ && getMaxInterval() != null) { @Override public void delete(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.cosmosDBAccounts().deleteById(getId()); } diff --git a/src/main/java/gyro/azure/dns/ARecordSetFinder.java b/src/main/java/gyro/azure/dns/ARecordSetFinder.java index 27431ad9..d39ffb1b 100644 --- a/src/main/java/gyro/azure/dns/ARecordSetFinder.java +++ b/src/main/java/gyro/azure/dns/ARecordSetFinder.java @@ -20,7 +20,7 @@ import com.azure.resourcemanager.dns.models.ARecordSet; import com.azure.resourcemanager.dns.models.DnsZone; import com.psddev.dari.util.ObjectUtils; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.GyroException; import gyro.core.Type; @@ -40,7 +40,7 @@ * a-record-set: $(external-query azure::a-record-set {}) */ @Type("a-record-set") -public class ARecordSetFinder extends AzureResourceManagerFinder { +public class ARecordSetFinder extends AzureFinder { private String dnsZoneId; private String name; diff --git a/src/main/java/gyro/azure/dns/ARecordSetResource.java b/src/main/java/gyro/azure/dns/ARecordSetResource.java index f54f3dc9..8605b83f 100644 --- a/src/main/java/gyro/azure/dns/ARecordSetResource.java +++ b/src/main/java/gyro/azure/dns/ARecordSetResource.java @@ -160,7 +160,7 @@ public void copyFrom(ARecordSet aRecordSet) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); com.azure.resourcemanager.dns.models.ARecordSet aRecordSet = client.dnsZones() .getById(getDnsZone().getId()) @@ -178,7 +178,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); DnsRecordSet.UpdateDefinitionStages.ARecordSetBlank updateARecordSetBlank = client.dnsZones() .getById(getDnsZone().getId()) @@ -205,7 +205,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); DnsRecordSet.UpdateARecordSet updateARecordSet = client.dnsZones().getById(getDnsZone().getId()).update().updateARecordSet(getName()); @@ -254,7 +254,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.dnsZones().getById(getDnsZone().getId()).update().withoutARecordSet(getName()).apply(); } diff --git a/src/main/java/gyro/azure/dns/AaaaRecordSetFinder.java b/src/main/java/gyro/azure/dns/AaaaRecordSetFinder.java index f9cd50bf..bb8a498e 100644 --- a/src/main/java/gyro/azure/dns/AaaaRecordSetFinder.java +++ b/src/main/java/gyro/azure/dns/AaaaRecordSetFinder.java @@ -20,7 +20,7 @@ import com.azure.resourcemanager.dns.models.AaaaRecordSet; import com.azure.resourcemanager.dns.models.DnsZone; import com.psddev.dari.util.ObjectUtils; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.GyroException; import gyro.core.Type; @@ -40,7 +40,7 @@ * aaaa-record-set: $(external-query azure::aaaa-record-set {}) */ @Type("aaaa-record-set") -public class AaaaRecordSetFinder extends AzureResourceManagerFinder { +public class AaaaRecordSetFinder extends AzureFinder { private String dnsZoneId; private String name; diff --git a/src/main/java/gyro/azure/dns/AaaaRecordSetResource.java b/src/main/java/gyro/azure/dns/AaaaRecordSetResource.java index f5ffd64b..3cd4449d 100644 --- a/src/main/java/gyro/azure/dns/AaaaRecordSetResource.java +++ b/src/main/java/gyro/azure/dns/AaaaRecordSetResource.java @@ -163,7 +163,7 @@ public void copyFrom(AaaaRecordSet aaaaRecordSet) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); AaaaRecordSet aaaaRecordSet = client.dnsZones().getById(getDnsZone().getId()).aaaaRecordSets().getByName(getName()); @@ -178,7 +178,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); DnsRecordSet.UpdateDefinitionStages.AaaaRecordSetBlank defineAaaaRecordSet = client.dnsZones().getById(getDnsZone().getId()).update().defineAaaaRecordSet(getName()); @@ -203,7 +203,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); DnsRecordSet.UpdateAaaaRecordSet updateAaaaRecordSet = client.dnsZones().getById(getDnsZone().getId()).update().updateAaaaRecordSet(getName()); @@ -252,7 +252,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.dnsZones().getById(getDnsZone().getId()).update().withoutAaaaRecordSet(getName()).apply(); } diff --git a/src/main/java/gyro/azure/dns/CaaRecordSetFinder.java b/src/main/java/gyro/azure/dns/CaaRecordSetFinder.java index 69151a02..407b5b53 100644 --- a/src/main/java/gyro/azure/dns/CaaRecordSetFinder.java +++ b/src/main/java/gyro/azure/dns/CaaRecordSetFinder.java @@ -20,7 +20,7 @@ import com.azure.resourcemanager.dns.models.CaaRecordSet; import com.azure.resourcemanager.dns.models.DnsZone; import com.psddev.dari.util.ObjectUtils; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.GyroException; import gyro.core.Type; @@ -40,7 +40,7 @@ * caa-record-set: $(external-query azure::caa-record-set {}) */ @Type("caa-record-set") -public class CaaRecordSetFinder extends AzureResourceManagerFinder { +public class CaaRecordSetFinder extends AzureFinder { private String dnsZoneId; private String name; diff --git a/src/main/java/gyro/azure/dns/CaaRecordSetResource.java b/src/main/java/gyro/azure/dns/CaaRecordSetResource.java index dc21dea9..75102bb3 100644 --- a/src/main/java/gyro/azure/dns/CaaRecordSetResource.java +++ b/src/main/java/gyro/azure/dns/CaaRecordSetResource.java @@ -179,7 +179,7 @@ public void copyFrom(CaaRecordSet caaRecordSet) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); CaaRecordSet caaRecordSet = client.dnsZones().getById(getDnsZone().getId()).caaRecordSets().getByName(getName()); @@ -194,7 +194,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); DnsRecordSet.UpdateDefinitionStages.CaaRecordSetBlank defineCaaRecordSet = client.dnsZones() @@ -225,7 +225,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); DnsRecordSet.UpdateCaaRecordSet updateCaaRecordSet = client.dnsZones().getById(getDnsZone().getId()).update().updateCaaRecordSet(getName()); @@ -272,7 +272,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.dnsZones().getById(getDnsZone().getId()).update().withoutCaaRecordSet(getName()).apply(); } diff --git a/src/main/java/gyro/azure/dns/CnameRecordSetFinder.java b/src/main/java/gyro/azure/dns/CnameRecordSetFinder.java index 0e732416..2178e503 100644 --- a/src/main/java/gyro/azure/dns/CnameRecordSetFinder.java +++ b/src/main/java/gyro/azure/dns/CnameRecordSetFinder.java @@ -20,7 +20,7 @@ import com.azure.resourcemanager.dns.models.DnsZone; import com.azure.resourcemanager.dns.models.CnameRecordSet; import com.psddev.dari.util.ObjectUtils; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.GyroException; import gyro.core.Type; @@ -40,7 +40,7 @@ * cname-record-set: $(external-query azure::cname-record-set {}) */ @Type("cname-record-set") -public class CnameRecordSetFinder extends AzureResourceManagerFinder { +public class CnameRecordSetFinder extends AzureFinder { private String dnsZoneId; private String name; diff --git a/src/main/java/gyro/azure/dns/CnameRecordSetResource.java b/src/main/java/gyro/azure/dns/CnameRecordSetResource.java index 58d6789e..6b823d26 100644 --- a/src/main/java/gyro/azure/dns/CnameRecordSetResource.java +++ b/src/main/java/gyro/azure/dns/CnameRecordSetResource.java @@ -153,7 +153,7 @@ public void copyFrom(CnameRecordSet cnameRecordSet) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); CnameRecordSet cnameRecordSet = client.dnsZones().getById(getDnsZone().getId()).cNameRecordSets().getByName(getName()); @@ -168,7 +168,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); DnsRecordSet.UpdateDefinitionStages.WithCNameRecordSetAttachable createCNameRecordSet = client.dnsZones() .getById(getDnsZone().getId()) @@ -191,7 +191,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); DnsRecordSet.UpdateCNameRecordSet updateCNameRecordSet = client.dnsZones().getById(getDnsZone().getId()).update().updateCNameRecordSet(getName()); @@ -230,7 +230,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.dnsZones().getById(getDnsZone().getId()).update().withoutCaaRecordSet(getName()).apply(); } diff --git a/src/main/java/gyro/azure/dns/DnsZoneFinder.java b/src/main/java/gyro/azure/dns/DnsZoneFinder.java index ea798b25..82dd0abb 100644 --- a/src/main/java/gyro/azure/dns/DnsZoneFinder.java +++ b/src/main/java/gyro/azure/dns/DnsZoneFinder.java @@ -19,7 +19,7 @@ import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.dns.models.DnsZone; import com.psddev.dari.util.ObjectUtils; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.GyroException; import gyro.core.Type; @@ -39,7 +39,7 @@ * dns-zone: $(external-query azure::dns-zone {}) */ @Type("dns-zone") -public class DnsZoneFinder extends AzureResourceManagerFinder { +public class DnsZoneFinder extends AzureFinder { private String id; /** diff --git a/src/main/java/gyro/azure/dns/DnsZoneResource.java b/src/main/java/gyro/azure/dns/DnsZoneResource.java index 89c44c2f..d423aaa5 100644 --- a/src/main/java/gyro/azure/dns/DnsZoneResource.java +++ b/src/main/java/gyro/azure/dns/DnsZoneResource.java @@ -168,7 +168,7 @@ public void copyFrom(DnsZone dnsZone) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); DnsZone dnsZone = client.dnsZones().getById(getId()); @@ -183,7 +183,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); DnsZone.DefinitionStages.WithCreate withCreate; @@ -200,7 +200,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); DnsZone.Update update = client.dnsZones().getById(getId()).update(); @@ -213,7 +213,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.dnsZones().deleteById(getId()); } diff --git a/src/main/java/gyro/azure/dns/MxRecordSetFinder.java b/src/main/java/gyro/azure/dns/MxRecordSetFinder.java index ac8527da..7de2405a 100644 --- a/src/main/java/gyro/azure/dns/MxRecordSetFinder.java +++ b/src/main/java/gyro/azure/dns/MxRecordSetFinder.java @@ -20,7 +20,7 @@ import com.azure.resourcemanager.dns.models.DnsZone; import com.azure.resourcemanager.dns.models.MxRecordSet; import com.psddev.dari.util.ObjectUtils; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.GyroException; import gyro.core.Type; @@ -40,7 +40,7 @@ * mx-record-set: $(external-query azure::mx-record-set {}) */ @Type("mx-record-set") -public class MxRecordSetFinder extends AzureResourceManagerFinder { +public class MxRecordSetFinder extends AzureFinder { private String dnsZoneId; private String name; diff --git a/src/main/java/gyro/azure/dns/MxRecordSetResource.java b/src/main/java/gyro/azure/dns/MxRecordSetResource.java index b2e24ae1..807ab752 100644 --- a/src/main/java/gyro/azure/dns/MxRecordSetResource.java +++ b/src/main/java/gyro/azure/dns/MxRecordSetResource.java @@ -177,7 +177,7 @@ public void copyFrom(MxRecordSet mxRecordSet) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); MxRecordSet mxRecordSet = client.dnsZones().getById(getDnsZone().getId()).mxRecordSets().getByName(getName()); @@ -192,7 +192,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); DnsRecordSet.UpdateDefinitionStages.MXRecordSetBlank defineMXRecordSet = client.dnsZones() .getById(getDnsZone().getId()) @@ -221,7 +221,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); DnsRecordSet.UpdateMXRecordSet updateMXRecordSet = client.dnsZones().getById(getDnsZone().getId()).update().updateMXRecordSet(getName()); @@ -281,7 +281,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.dnsZones().getById(getDnsZone().getId()).update().withoutMXRecordSet(getName()).apply(); } diff --git a/src/main/java/gyro/azure/dns/PtrRecordSetFinder.java b/src/main/java/gyro/azure/dns/PtrRecordSetFinder.java index d9e04642..34e69e47 100644 --- a/src/main/java/gyro/azure/dns/PtrRecordSetFinder.java +++ b/src/main/java/gyro/azure/dns/PtrRecordSetFinder.java @@ -20,7 +20,7 @@ import com.azure.resourcemanager.dns.models.DnsZone; import com.azure.resourcemanager.dns.models.PtrRecordSet; import com.psddev.dari.util.ObjectUtils; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.GyroException; import gyro.core.Type; @@ -40,7 +40,7 @@ * ptr-record-set: $(external-query azure::ptr-record-set {}) */ @Type("ptr-record-set") -public class PtrRecordSetFinder extends AzureResourceManagerFinder { +public class PtrRecordSetFinder extends AzureFinder { private String dnsZoneId; private String name; diff --git a/src/main/java/gyro/azure/dns/PtrRecordSetResource.java b/src/main/java/gyro/azure/dns/PtrRecordSetResource.java index 8fcd9b71..0b9a4978 100644 --- a/src/main/java/gyro/azure/dns/PtrRecordSetResource.java +++ b/src/main/java/gyro/azure/dns/PtrRecordSetResource.java @@ -161,7 +161,7 @@ public void copyFrom(PtrRecordSet ptrRecordSet) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); PtrRecordSet ptrRecordSet = client.dnsZones().getById(getDnsZone().getId()).ptrRecordSets().getByName(getName()); @@ -175,7 +175,7 @@ public boolean refresh() { } public void create(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); DnsRecordSet.UpdateDefinitionStages.PtrRecordSetBlank definePtrRecordSet = client.dnsZones() .getById(getDnsZone().getId()) @@ -203,7 +203,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); DnsRecordSet.UpdatePtrRecordSet updatePtrRecordSet = client.dnsZones().getById(getDnsZone().getId()).update().updatePtrRecordSet(getName()); @@ -252,7 +252,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.dnsZones().getById(getDnsZone().getId()).update().withoutPtrRecordSet(getName()).apply(); } diff --git a/src/main/java/gyro/azure/dns/SrvRecordSetFinder.java b/src/main/java/gyro/azure/dns/SrvRecordSetFinder.java index ec1f3878..3d30cc17 100644 --- a/src/main/java/gyro/azure/dns/SrvRecordSetFinder.java +++ b/src/main/java/gyro/azure/dns/SrvRecordSetFinder.java @@ -20,7 +20,7 @@ import com.azure.resourcemanager.dns.models.DnsZone; import com.azure.resourcemanager.dns.models.SrvRecordSet; import com.psddev.dari.util.ObjectUtils; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.GyroException; import gyro.core.Type; @@ -40,7 +40,7 @@ * srv-record-set: $(external-query azure::srv-record-set {}) */ @Type("srv-record-set") -public class SrvRecordSetFinder extends AzureResourceManagerFinder { +public class SrvRecordSetFinder extends AzureFinder { private String dnsZoneId; private String name; diff --git a/src/main/java/gyro/azure/dns/SrvRecordSetResource.java b/src/main/java/gyro/azure/dns/SrvRecordSetResource.java index 9a62690d..aaef32a4 100644 --- a/src/main/java/gyro/azure/dns/SrvRecordSetResource.java +++ b/src/main/java/gyro/azure/dns/SrvRecordSetResource.java @@ -174,7 +174,7 @@ public void copyFrom(SrvRecordSet srvRecordSet) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); SrvRecordSet srvRecordSet = client.dnsZones().getById(getDnsZone().getId()).srvRecordSets().getByName(getName()); @@ -189,7 +189,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); DnsRecordSet.UpdateDefinitionStages.SrvRecordSetBlank defineSrvRecordSet = client.dnsZones() .getById(getDnsZone().getId()) @@ -216,7 +216,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); DnsRecordSet.UpdateSrvRecordSet updateSrvRecordSet = client.dnsZones().getById(getDnsZone().getId()).update().updateSrvRecordSet(getName()); @@ -262,7 +262,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.dnsZones().getById(getDnsZone().getId()).update().withoutSrvRecordSet(getName()).apply(); } diff --git a/src/main/java/gyro/azure/dns/TxtRecordSetFinder.java b/src/main/java/gyro/azure/dns/TxtRecordSetFinder.java index 2b02f028..cde37c52 100644 --- a/src/main/java/gyro/azure/dns/TxtRecordSetFinder.java +++ b/src/main/java/gyro/azure/dns/TxtRecordSetFinder.java @@ -20,7 +20,7 @@ import com.azure.resourcemanager.dns.models.DnsZone; import com.azure.resourcemanager.dns.models.TxtRecordSet; import com.psddev.dari.util.ObjectUtils; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.GyroException; import gyro.core.Type; @@ -40,7 +40,7 @@ * txt-record-set: $(external-query azure::txt-record-set {}) */ @Type("txt-record-set") -public class TxtRecordSetFinder extends AzureResourceManagerFinder { +public class TxtRecordSetFinder extends AzureFinder { private String dnsZoneId; private String name; diff --git a/src/main/java/gyro/azure/dns/TxtRecordSetResource.java b/src/main/java/gyro/azure/dns/TxtRecordSetResource.java index 7be02092..54b9447e 100644 --- a/src/main/java/gyro/azure/dns/TxtRecordSetResource.java +++ b/src/main/java/gyro/azure/dns/TxtRecordSetResource.java @@ -162,7 +162,7 @@ public void copyFrom(TxtRecordSet txtRecordSet) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); TxtRecordSet txtRecordSet = client.dnsZones().getById(getDnsZone().getId()).txtRecordSets().getByName(getName()); @@ -177,7 +177,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); DnsRecordSet.UpdateDefinitionStages.TxtRecordSetBlank defineTxtRecordSet = client.dnsZones() .getById(getDnsZone().getId()) @@ -204,7 +204,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); DnsRecordSet.UpdateTxtRecordSet updateTxtRecordSet = client.dnsZones().getById(getDnsZone().getId()).update().updateTxtRecordSet(getName()); @@ -253,7 +253,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.dnsZones().getById(getDnsZone().getId()).update().withoutTxtRecordSet(getName()).apply(); } diff --git a/src/main/java/gyro/azure/identity/IdentityFinder.java b/src/main/java/gyro/azure/identity/IdentityFinder.java index 0f04e0b9..b3e8f259 100644 --- a/src/main/java/gyro/azure/identity/IdentityFinder.java +++ b/src/main/java/gyro/azure/identity/IdentityFinder.java @@ -18,7 +18,7 @@ import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.msi.models.Identity; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.Type; import java.util.Collections; @@ -37,7 +37,7 @@ * identity: $(external-query azure::identity {}) */ @Type("identity") -public class IdentityFinder extends AzureResourceManagerFinder { +public class IdentityFinder extends AzureFinder { private String id; /** diff --git a/src/main/java/gyro/azure/identity/IdentityResource.java b/src/main/java/gyro/azure/identity/IdentityResource.java index dad97b47..0f387215 100644 --- a/src/main/java/gyro/azure/identity/IdentityResource.java +++ b/src/main/java/gyro/azure/identity/IdentityResource.java @@ -164,7 +164,7 @@ public void copyFrom(Identity identity) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); Identity identity = client.identities().getById(getId()); @@ -179,7 +179,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) throws Exception { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); Identity identity = client.identities().define(getName()) .withRegion(Region.fromName(getRegion())) @@ -192,7 +192,7 @@ public void create(GyroUI ui, State state) throws Exception { @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) throws Exception { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); Identity.Update update = client.identities().getById(getId()).update(); IdentityResource oldResource = (IdentityResource) current; @@ -212,7 +212,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) throws Exception { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.identities().deleteById(getId()); } diff --git a/src/main/java/gyro/azure/keyvault/KeyVaultCertificateFinder.java b/src/main/java/gyro/azure/keyvault/KeyVaultCertificateFinder.java index 1d9677e7..f885c0f5 100644 --- a/src/main/java/gyro/azure/keyvault/KeyVaultCertificateFinder.java +++ b/src/main/java/gyro/azure/keyvault/KeyVaultCertificateFinder.java @@ -26,7 +26,7 @@ import com.azure.security.keyvault.certificates.CertificateClient; import com.azure.security.keyvault.certificates.CertificateClientBuilder; import com.azure.security.keyvault.certificates.models.KeyVaultCertificateWithPolicy; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.Type; /** @@ -40,7 +40,7 @@ * certificate: $(external-query azure::key-vault-certificate {resource-group: "resource-group-example", vault: "vault-example", name: "certificate-example"}) */ @Type("key-vault-certificate") -public class KeyVaultCertificateFinder extends AzureResourceManagerFinder { +public class KeyVaultCertificateFinder extends AzureFinder { private String resourceGroup; private String vault; diff --git a/src/main/java/gyro/azure/keyvault/KeyVaultFinder.java b/src/main/java/gyro/azure/keyvault/KeyVaultFinder.java index 3d9bae46..28b30190 100644 --- a/src/main/java/gyro/azure/keyvault/KeyVaultFinder.java +++ b/src/main/java/gyro/azure/keyvault/KeyVaultFinder.java @@ -24,7 +24,7 @@ import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.keyvault.models.Vault; import com.azure.resourcemanager.resources.fluentcore.arm.models.HasName; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.Type; /** @@ -38,7 +38,7 @@ * identity: $(external-query azure::key-vault {resource-group: "resource-group-example", name: "vault-example"}) */ @Type("key-vault") -public class KeyVaultFinder extends AzureResourceManagerFinder { +public class KeyVaultFinder extends AzureFinder { private String resourceGroup; private String name; diff --git a/src/main/java/gyro/azure/keyvault/KeyVaultKeyFinder.java b/src/main/java/gyro/azure/keyvault/KeyVaultKeyFinder.java index 80f2625d..6b5d510a 100644 --- a/src/main/java/gyro/azure/keyvault/KeyVaultKeyFinder.java +++ b/src/main/java/gyro/azure/keyvault/KeyVaultKeyFinder.java @@ -7,7 +7,7 @@ import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.keyvault.models.Key; import com.azure.resourcemanager.keyvault.models.Vault; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.Type; /** @@ -21,7 +21,7 @@ * certificate: $(external-query azure::key-vault-key {resource-group: "resource-group-example", vault: "vault-example", name: "key-example"}) */ @Type("key-vault-key") -public class KeyVaultKeyFinder extends AzureResourceManagerFinder { +public class KeyVaultKeyFinder extends AzureFinder { private String resourceGroup; private String vault; diff --git a/src/main/java/gyro/azure/keyvault/KeyVaultResource.java b/src/main/java/gyro/azure/keyvault/KeyVaultResource.java index f7193baf..ed066dc2 100644 --- a/src/main/java/gyro/azure/keyvault/KeyVaultResource.java +++ b/src/main/java/gyro/azure/keyvault/KeyVaultResource.java @@ -386,7 +386,7 @@ public void copyFrom(Vault vault) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); Vault vault = client.vaults().getByResourceGroup(getResourceGroup().getName(), getName()); @@ -401,7 +401,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) throws Exception { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); Vault.DefinitionStages.WithCreate withCreate = client.vaults().define(getName()) .withRegion(Region.fromName(getRegion())) @@ -443,7 +443,7 @@ public void create(GyroUI ui, State state) throws Exception { @Override public void update( GyroUI ui, State state, Resource current, Set changedFieldNames) throws Exception { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); Vault vault = client.vaults().getById(getId()); @@ -506,7 +506,7 @@ public void update( @Override public void delete(GyroUI ui, State state) throws Exception { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.vaults().deleteById(getId()); @@ -516,7 +516,7 @@ public void delete(GyroUI ui, State state) throws Exception { } Vault getKeyVault() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); return client.vaults().getByResourceGroup(getResourceGroup().getName(), getName()); } diff --git a/src/main/java/gyro/azure/keyvault/KeyVaultSecretFinder.java b/src/main/java/gyro/azure/keyvault/KeyVaultSecretFinder.java index e14f017a..d30a964c 100644 --- a/src/main/java/gyro/azure/keyvault/KeyVaultSecretFinder.java +++ b/src/main/java/gyro/azure/keyvault/KeyVaultSecretFinder.java @@ -23,7 +23,7 @@ import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.keyvault.models.Secret; import com.azure.resourcemanager.keyvault.models.Vault; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.Type; /** @@ -37,7 +37,7 @@ * certificate: $(external-query azure::key-vault-secret {resource-group: "resource-group-example", vault: "vault-example", name: "secret-example"}) */ @Type("key-vault-secret") -public class KeyVaultSecretFinder extends AzureResourceManagerFinder { +public class KeyVaultSecretFinder extends AzureFinder { private String resourceGroup; private String vault; diff --git a/src/main/java/gyro/azure/network/ApplicationGatewayFinder.java b/src/main/java/gyro/azure/network/ApplicationGatewayFinder.java index bd4b4a41..13b1d873 100644 --- a/src/main/java/gyro/azure/network/ApplicationGatewayFinder.java +++ b/src/main/java/gyro/azure/network/ApplicationGatewayFinder.java @@ -23,7 +23,7 @@ import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.network.models.ApplicationGateway; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.Type; /** @@ -38,7 +38,7 @@ */ @Type("application-gateway") public class ApplicationGatewayFinder - extends AzureResourceManagerFinder { + extends AzureFinder { private String id; diff --git a/src/main/java/gyro/azure/network/ApplicationGatewayResource.java b/src/main/java/gyro/azure/network/ApplicationGatewayResource.java index b14d0038..76a637c0 100644 --- a/src/main/java/gyro/azure/network/ApplicationGatewayResource.java +++ b/src/main/java/gyro/azure/network/ApplicationGatewayResource.java @@ -547,7 +547,7 @@ public Map backendHealth() { Map healthMap = new HashMap<>(); int total = 0; - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); ApplicationGateway applicationGateway = client.applicationGateways().getById(getId()); if (applicationGateway != null) { @@ -655,7 +655,7 @@ public void copyFrom(ApplicationGateway applicationGateway) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); ApplicationGateway applicationGateway = client.applicationGateways().getById(getId()); @@ -670,7 +670,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); ApplicationGateway.DefinitionStages.WithRequestRoutingRule withRequestRoutingRule = client.applicationGateways() .define(getName()).withRegion(Region.fromName(getRegion())) @@ -735,7 +735,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource resource, Set changedFieldNames) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); ApplicationGateway applicationGateway = client.applicationGateways().getById(getId()); @@ -774,7 +774,7 @@ public void update(GyroUI ui, State state, Resource resource, Set change @Override public void delete(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.applicationGateways().deleteById(getId()); } diff --git a/src/main/java/gyro/azure/network/ApplicationSecurityGroupFinder.java b/src/main/java/gyro/azure/network/ApplicationSecurityGroupFinder.java index c16a8158..729f4702 100644 --- a/src/main/java/gyro/azure/network/ApplicationSecurityGroupFinder.java +++ b/src/main/java/gyro/azure/network/ApplicationSecurityGroupFinder.java @@ -23,7 +23,7 @@ import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.network.models.ApplicationSecurityGroup; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.Type; /** @@ -38,7 +38,7 @@ */ @Type("application-security-group") public class ApplicationSecurityGroupFinder - extends AzureResourceManagerFinder { + extends AzureFinder { private String id; diff --git a/src/main/java/gyro/azure/network/ApplicationSecurityGroupResource.java b/src/main/java/gyro/azure/network/ApplicationSecurityGroupResource.java index 1208b879..537636c7 100644 --- a/src/main/java/gyro/azure/network/ApplicationSecurityGroupResource.java +++ b/src/main/java/gyro/azure/network/ApplicationSecurityGroupResource.java @@ -180,7 +180,7 @@ public void copyFrom(ApplicationSecurityGroup applicationSecurityGroup) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); ApplicationSecurityGroup applicationSecurityGroup = client.applicationSecurityGroups().getById(getId()); @@ -195,7 +195,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); ApplicationSecurityGroup applicationSecurityGroup = client.applicationSecurityGroups().define(getName()) .withRegion(Region.fromName(getRegion())) @@ -208,14 +208,14 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.applicationSecurityGroups().getById(getId()).update().withTags(getTags()).apply(); } @Override public void delete(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.applicationSecurityGroups().deleteById(getId()); } diff --git a/src/main/java/gyro/azure/network/LoadBalancerFinder.java b/src/main/java/gyro/azure/network/LoadBalancerFinder.java index 9cb4f64e..d9c9246a 100644 --- a/src/main/java/gyro/azure/network/LoadBalancerFinder.java +++ b/src/main/java/gyro/azure/network/LoadBalancerFinder.java @@ -23,7 +23,7 @@ import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.network.models.LoadBalancer; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.Type; /** @@ -37,7 +37,7 @@ * load-balancer: $(external-query azure::load-balancer {}) */ @Type("load-balancer") -public class LoadBalancerFinder extends AzureResourceManagerFinder { +public class LoadBalancerFinder extends AzureFinder { private String id; diff --git a/src/main/java/gyro/azure/network/LoadBalancerResource.java b/src/main/java/gyro/azure/network/LoadBalancerResource.java index a1111bff..b2004d77 100644 --- a/src/main/java/gyro/azure/network/LoadBalancerResource.java +++ b/src/main/java/gyro/azure/network/LoadBalancerResource.java @@ -386,7 +386,7 @@ public void copyFrom(LoadBalancer loadBalancer) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); LoadBalancer loadBalancer = client.loadBalancers().getById(getId()); @@ -401,7 +401,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); LoadBalancer.DefinitionStages.WithLBRuleOrNat lb = client.loadBalancers() .define(getName()) @@ -506,7 +506,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); LoadBalancer loadBalancer = client.loadBalancers().getById(getId()); @@ -633,7 +633,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.loadBalancers().deleteByResourceGroup(getResourceGroup().getName(), getName()); } diff --git a/src/main/java/gyro/azure/network/NetworkFinder.java b/src/main/java/gyro/azure/network/NetworkFinder.java index c3be4fd0..7cb963cc 100644 --- a/src/main/java/gyro/azure/network/NetworkFinder.java +++ b/src/main/java/gyro/azure/network/NetworkFinder.java @@ -23,11 +23,11 @@ import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.network.models.Network; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.Type; @Type("network") -public class NetworkFinder extends AzureResourceManagerFinder { +public class NetworkFinder extends AzureFinder { private String id; diff --git a/src/main/java/gyro/azure/network/NetworkInterfaceFinder.java b/src/main/java/gyro/azure/network/NetworkInterfaceFinder.java index f290dbb2..0ef56833 100644 --- a/src/main/java/gyro/azure/network/NetworkInterfaceFinder.java +++ b/src/main/java/gyro/azure/network/NetworkInterfaceFinder.java @@ -23,7 +23,7 @@ import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.network.models.NetworkInterface; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.Type; /** @@ -37,7 +37,7 @@ * network-interface: $(external-query azure::network-interface {}) */ @Type("network-interface") -public class NetworkInterfaceFinder extends AzureResourceManagerFinder { +public class NetworkInterfaceFinder extends AzureFinder { private String id; diff --git a/src/main/java/gyro/azure/network/NetworkInterfaceResource.java b/src/main/java/gyro/azure/network/NetworkInterfaceResource.java index 51958d47..cad29c4c 100644 --- a/src/main/java/gyro/azure/network/NetworkInterfaceResource.java +++ b/src/main/java/gyro/azure/network/NetworkInterfaceResource.java @@ -223,7 +223,7 @@ public void copyFrom(NetworkInterface networkInterface) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); NetworkInterface networkInterface = getNetworkInterface(client); @@ -238,7 +238,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); NetworkInterface.DefinitionStages.WithPrimaryPrivateIP withPrimaryPrivateIP = client.networkInterfaces() .define(getName()) @@ -286,7 +286,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); NetworkInterface networkInterface = getNetworkInterface(client); @@ -316,7 +316,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.networkInterfaces().deleteByResourceGroup(getResourceGroup().getName(), getName()); } diff --git a/src/main/java/gyro/azure/network/NetworkResource.java b/src/main/java/gyro/azure/network/NetworkResource.java index f65818d7..e72508ab 100644 --- a/src/main/java/gyro/azure/network/NetworkResource.java +++ b/src/main/java/gyro/azure/network/NetworkResource.java @@ -245,7 +245,7 @@ public void copyFrom(Network network) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); Network network = client.networks().getById(getId()); @@ -260,7 +260,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); Network.DefinitionStages.WithCreate networkDefWithoutAddress = client.networks() .define(getName()) @@ -284,7 +284,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); Network network = client.networks().getById(getId()); @@ -322,7 +322,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.networks().deleteById(getId()); } diff --git a/src/main/java/gyro/azure/network/NetworkSecurityGroupFinder.java b/src/main/java/gyro/azure/network/NetworkSecurityGroupFinder.java index d184aa1e..0f2b70d0 100644 --- a/src/main/java/gyro/azure/network/NetworkSecurityGroupFinder.java +++ b/src/main/java/gyro/azure/network/NetworkSecurityGroupFinder.java @@ -23,7 +23,7 @@ import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.network.models.NetworkSecurityGroup; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.Type; /** @@ -38,7 +38,7 @@ */ @Type("network-security-group") public class NetworkSecurityGroupFinder - extends AzureResourceManagerFinder { + extends AzureFinder { private String id; diff --git a/src/main/java/gyro/azure/network/NetworkSecurityGroupResource.java b/src/main/java/gyro/azure/network/NetworkSecurityGroupResource.java index 0ee6f1b0..06fdd0a5 100644 --- a/src/main/java/gyro/azure/network/NetworkSecurityGroupResource.java +++ b/src/main/java/gyro/azure/network/NetworkSecurityGroupResource.java @@ -171,7 +171,7 @@ public void copyFrom(NetworkSecurityGroup networkSecurityGroup) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); NetworkSecurityGroup networkSecurityGroup = client.networkSecurityGroups().getById(getId()); @@ -186,7 +186,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); NetworkSecurityGroup networkSecurityGroup = client.networkSecurityGroups() .define(getName()) @@ -200,7 +200,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); NetworkSecurityGroup networkSecurityGroup = client.networkSecurityGroups().getById(getId()); @@ -209,7 +209,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.networkSecurityGroups().deleteById(getId()); } diff --git a/src/main/java/gyro/azure/network/NetworkSecurityGroupRuleResource.java b/src/main/java/gyro/azure/network/NetworkSecurityGroupRuleResource.java index 8b128a03..c2162df9 100644 --- a/src/main/java/gyro/azure/network/NetworkSecurityGroupRuleResource.java +++ b/src/main/java/gyro/azure/network/NetworkSecurityGroupRuleResource.java @@ -290,7 +290,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); NetworkSecurityGroupResource parent = (NetworkSecurityGroupResource) parent(); @@ -356,7 +356,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); NetworkSecurityGroupResource parent = (NetworkSecurityGroupResource) parent(); @@ -411,7 +411,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); NetworkSecurityGroupResource parent = (NetworkSecurityGroupResource) parent(); diff --git a/src/main/java/gyro/azure/network/NicIpConfigurationResource.java b/src/main/java/gyro/azure/network/NicIpConfigurationResource.java index 8bb8253b..7dc70608 100644 --- a/src/main/java/gyro/azure/network/NicIpConfigurationResource.java +++ b/src/main/java/gyro/azure/network/NicIpConfigurationResource.java @@ -185,7 +185,7 @@ public void create(GyroUI ui, State state) { return; } - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); NetworkInterfaceResource parent = (NetworkInterfaceResource) parent(); @@ -229,7 +229,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); NetworkInterfaceResource parent = (NetworkInterfaceResource) parent(); @@ -303,7 +303,7 @@ public void delete(GyroUI ui, State state) { return; } - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); NetworkInterfaceResource parent = (NetworkInterfaceResource) parent(); diff --git a/src/main/java/gyro/azure/network/PublicIpAddressFinder.java b/src/main/java/gyro/azure/network/PublicIpAddressFinder.java index d1ab9d84..61e4c2e7 100644 --- a/src/main/java/gyro/azure/network/PublicIpAddressFinder.java +++ b/src/main/java/gyro/azure/network/PublicIpAddressFinder.java @@ -23,7 +23,7 @@ import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.network.models.PublicIpAddress; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.Type; /** @@ -37,7 +37,7 @@ * public-ip-address: $(external-query azure::public-ip-address {}) */ @Type("public-ip-address") -public class PublicIpAddressFinder extends AzureResourceManagerFinder { +public class PublicIpAddressFinder extends AzureFinder { private String id; diff --git a/src/main/java/gyro/azure/network/PublicIpAddressResource.java b/src/main/java/gyro/azure/network/PublicIpAddressResource.java index 9741e500..fe21d5e3 100644 --- a/src/main/java/gyro/azure/network/PublicIpAddressResource.java +++ b/src/main/java/gyro/azure/network/PublicIpAddressResource.java @@ -319,7 +319,7 @@ public void copyFrom(PublicIpAddress publicIpAddress) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); PublicIpAddress publicIpAddress = client.publicIpAddresses().getById(getId()); @@ -334,7 +334,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); PublicIpAddress.DefinitionStages.WithCreate withCreate = client.publicIpAddresses() .define(getName()) @@ -382,7 +382,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); PublicIpAddress publicIpAddress = client.publicIpAddresses().getById(getId()); @@ -425,7 +425,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.publicIpAddresses().deleteById(getId()); } diff --git a/src/main/java/gyro/azure/network/RouteTableFinder.java b/src/main/java/gyro/azure/network/RouteTableFinder.java index 69943124..f9cbc5a2 100644 --- a/src/main/java/gyro/azure/network/RouteTableFinder.java +++ b/src/main/java/gyro/azure/network/RouteTableFinder.java @@ -23,7 +23,7 @@ import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.network.models.RouteTable; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.Type; /** @@ -37,7 +37,7 @@ * route-table: $(external-query azure::route-table {}) */ @Type("route-table") -public class RouteTableFinder extends AzureResourceManagerFinder { +public class RouteTableFinder extends AzureFinder { private String id; diff --git a/src/main/java/gyro/azure/network/RouteTableResource.java b/src/main/java/gyro/azure/network/RouteTableResource.java index a765aa04..5c657205 100644 --- a/src/main/java/gyro/azure/network/RouteTableResource.java +++ b/src/main/java/gyro/azure/network/RouteTableResource.java @@ -176,7 +176,7 @@ public void copyFrom(RouteTable routeTable) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); RouteTable routeTable = client.routeTables().getById(getId()); @@ -191,7 +191,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); RouteTable.DefinitionStages.WithCreate withCreate; withCreate = client.routeTables().define(getName()) @@ -220,7 +220,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); RouteTableResource currentResource = (RouteTableResource) current; @@ -255,7 +255,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.routeTables().deleteById(getId()); } diff --git a/src/main/java/gyro/azure/network/SubnetResource.java b/src/main/java/gyro/azure/network/SubnetResource.java index d60a7daf..6dccd472 100644 --- a/src/main/java/gyro/azure/network/SubnetResource.java +++ b/src/main/java/gyro/azure/network/SubnetResource.java @@ -160,7 +160,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); NetworkResource parent = (NetworkResource) parent(); @@ -190,7 +190,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); NetworkResource parent = (NetworkResource) parent(); @@ -237,7 +237,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); NetworkResource parent = (NetworkResource) parent(); diff --git a/src/main/java/gyro/azure/registries/RegistryFinder.java b/src/main/java/gyro/azure/registries/RegistryFinder.java index 09543d01..8ddfd5e2 100644 --- a/src/main/java/gyro/azure/registries/RegistryFinder.java +++ b/src/main/java/gyro/azure/registries/RegistryFinder.java @@ -23,7 +23,7 @@ import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.containerregistry.models.Registry; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.Type; /** @@ -37,7 +37,7 @@ * registry: $(external-query azure::registry {}) */ @Type("registry") -public class RegistryFinder extends AzureResourceManagerFinder { +public class RegistryFinder extends AzureFinder { private String id; diff --git a/src/main/java/gyro/azure/registries/RegistryResource.java b/src/main/java/gyro/azure/registries/RegistryResource.java index 13b055dc..d8bbe349 100644 --- a/src/main/java/gyro/azure/registries/RegistryResource.java +++ b/src/main/java/gyro/azure/registries/RegistryResource.java @@ -244,7 +244,7 @@ public void copyFrom(Registry registry) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); Registry registry = client.containerRegistries() .getByResourceGroup(getResourceGroup().getName(), getName()); @@ -260,7 +260,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) throws Exception { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); Registry.DefinitionStages.WithSku withSku = client.containerRegistries() .define(getName()) @@ -315,7 +315,7 @@ public void create(GyroUI ui, State state) throws Exception { @Override public void update( GyroUI ui, State state, Resource current, Set changedFieldNames) throws Exception { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); Registry registry = client.containerRegistries() .getByResourceGroup(getResourceGroup().getName(), getName()); @@ -366,7 +366,7 @@ public void update( @Override public void delete(GyroUI ui, State state) throws Exception { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.containerRegistries().deleteByResourceGroup(getResourceGroup().getName(), getName()); } diff --git a/src/main/java/gyro/azure/resources/ResourceGroupFinder.java b/src/main/java/gyro/azure/resources/ResourceGroupFinder.java index e442986c..5deb8fc8 100644 --- a/src/main/java/gyro/azure/resources/ResourceGroupFinder.java +++ b/src/main/java/gyro/azure/resources/ResourceGroupFinder.java @@ -18,7 +18,7 @@ import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.resources.models.ResourceGroup; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.Type; import java.util.Collections; @@ -37,7 +37,7 @@ * resource-group: $(external-query azure::resource-group {}) */ @Type("resource-group") -public class ResourceGroupFinder extends AzureResourceManagerFinder { +public class ResourceGroupFinder extends AzureFinder { private String name; /** diff --git a/src/main/java/gyro/azure/resources/ResourceGroupResource.java b/src/main/java/gyro/azure/resources/ResourceGroupResource.java index a8aaeff8..a772d5a1 100644 --- a/src/main/java/gyro/azure/resources/ResourceGroupResource.java +++ b/src/main/java/gyro/azure/resources/ResourceGroupResource.java @@ -107,7 +107,7 @@ public void copyFrom(ResourceGroup resourceGroup) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); if (!client.resourceGroups().contain(getName())) { return false; @@ -121,7 +121,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); ResourceGroup resourceGroup = client.resourceGroups() .define(getName()) @@ -134,7 +134,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); ResourceGroup resourceGroup = client.resourceGroups().getByName(getName()); @@ -143,7 +143,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.resourceGroups().deleteByName(getName()); } diff --git a/src/main/java/gyro/azure/sql/SqlDatabaseFinder.java b/src/main/java/gyro/azure/sql/SqlDatabaseFinder.java index 30383669..43738515 100644 --- a/src/main/java/gyro/azure/sql/SqlDatabaseFinder.java +++ b/src/main/java/gyro/azure/sql/SqlDatabaseFinder.java @@ -25,7 +25,7 @@ import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.sql.models.SqlDatabase; import com.azure.resourcemanager.sql.models.SqlServer; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.Type; /** @@ -39,7 +39,7 @@ * sql-database: $(external-query azure::sql-database {}) */ @Type("sql-database") -public class SqlDatabaseFinder extends AzureResourceManagerFinder { +public class SqlDatabaseFinder extends AzureFinder { private String sqlServerId; private String name; diff --git a/src/main/java/gyro/azure/sql/SqlDatabaseResource.java b/src/main/java/gyro/azure/sql/SqlDatabaseResource.java index e26f0b1d..35ab9bd8 100644 --- a/src/main/java/gyro/azure/sql/SqlDatabaseResource.java +++ b/src/main/java/gyro/azure/sql/SqlDatabaseResource.java @@ -330,7 +330,7 @@ public void copyFrom(SqlDatabase database) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); SqlDatabase database = getSqlDatabase(client); @@ -345,7 +345,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); SqlDatabaseOperations.DefinitionStages.WithAllDifferentOptions buildDatabase = client.sqlServers() .getById(getSqlServer().getId()) @@ -452,7 +452,7 @@ && getImportFromFilename() != null) { @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); SqlDatabase.Update update = getSqlDatabase(client).update(); @@ -492,7 +492,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); SqlDatabase sqlDatabase = getSqlDatabase(client); if (sqlDatabase != null) { diff --git a/src/main/java/gyro/azure/sql/SqlElasticPoolFinder.java b/src/main/java/gyro/azure/sql/SqlElasticPoolFinder.java index b1173923..361fd996 100644 --- a/src/main/java/gyro/azure/sql/SqlElasticPoolFinder.java +++ b/src/main/java/gyro/azure/sql/SqlElasticPoolFinder.java @@ -25,7 +25,7 @@ import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.sql.models.SqlElasticPool; import com.azure.resourcemanager.sql.models.SqlServer; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.Type; /** @@ -39,7 +39,7 @@ * sql-elastic-pool: $(external-query azure::sql-elastic-pool {}) */ @Type("sql-elastic-pool") -public class SqlElasticPoolFinder extends AzureResourceManagerFinder { +public class SqlElasticPoolFinder extends AzureFinder { private String sqlServerId; private String name; diff --git a/src/main/java/gyro/azure/sql/SqlElasticPoolResource.java b/src/main/java/gyro/azure/sql/SqlElasticPoolResource.java index 8a229a6d..f0095378 100644 --- a/src/main/java/gyro/azure/sql/SqlElasticPoolResource.java +++ b/src/main/java/gyro/azure/sql/SqlElasticPoolResource.java @@ -244,7 +244,7 @@ public void copyFrom(SqlElasticPool elasticPool) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); SqlElasticPool elasticPool = getSqlElasticPool(client); @@ -263,7 +263,7 @@ public void create(GyroUI ui, State state) { throw new GyroException("You must provide a sql server resource."); } - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); SqlElasticPoolOperations.DefinitionStages.WithEdition buildPool = client.sqlServers() .getById(getSqlServer().getId()) @@ -308,7 +308,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); SqlElasticPool.Update update = getSqlElasticPool(client).update(); @@ -337,7 +337,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); SqlElasticPool sqlElasticPool = getSqlElasticPool(client); diff --git a/src/main/java/gyro/azure/sql/SqlFailoverGroupFinder.java b/src/main/java/gyro/azure/sql/SqlFailoverGroupFinder.java index 6653b2fb..3ee123f8 100644 --- a/src/main/java/gyro/azure/sql/SqlFailoverGroupFinder.java +++ b/src/main/java/gyro/azure/sql/SqlFailoverGroupFinder.java @@ -25,7 +25,7 @@ import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.sql.models.SqlFailoverGroup; import com.azure.resourcemanager.sql.models.SqlServer; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.Type; /** @@ -39,7 +39,7 @@ * sql-failover-group: $(external-query azure::sql-failover-group {}) */ @Type("sql-failover-group") -public class SqlFailoverGroupFinder extends AzureResourceManagerFinder { +public class SqlFailoverGroupFinder extends AzureFinder { private String sqlServerId; private String name; diff --git a/src/main/java/gyro/azure/sql/SqlFailoverGroupResource.java b/src/main/java/gyro/azure/sql/SqlFailoverGroupResource.java index 02589802..f5bd9528 100644 --- a/src/main/java/gyro/azure/sql/SqlFailoverGroupResource.java +++ b/src/main/java/gyro/azure/sql/SqlFailoverGroupResource.java @@ -210,7 +210,7 @@ public void copyFrom(SqlFailoverGroup failoverGroup) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); SqlFailoverGroup failoverGroup = getSqlFailoverGroup(client); @@ -225,7 +225,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); SqlFailoverGroupOperations.DefinitionStages.WithReadWriteEndpointPolicy buildFailoverGroup = client.sqlServers() .getById(getSqlServer().getId()) @@ -267,7 +267,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); SqlFailoverGroup.Update update = getSqlFailoverGroup(client).update(); @@ -309,7 +309,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); SqlFailoverGroup sqlFailoverGroup = getSqlFailoverGroup(client); diff --git a/src/main/java/gyro/azure/sql/SqlFirewallRuleFinder.java b/src/main/java/gyro/azure/sql/SqlFirewallRuleFinder.java index d5e7e478..6f36493b 100644 --- a/src/main/java/gyro/azure/sql/SqlFirewallRuleFinder.java +++ b/src/main/java/gyro/azure/sql/SqlFirewallRuleFinder.java @@ -25,7 +25,7 @@ import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.sql.models.SqlFirewallRule; import com.azure.resourcemanager.sql.models.SqlServer; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.Type; /** @@ -39,7 +39,7 @@ * sql-firewall-rule: $(external-query azure::sql-firewall-rule {}) */ @Type("sql-firewall-rule") -public class SqlFirewallRuleFinder extends AzureResourceManagerFinder { +public class SqlFirewallRuleFinder extends AzureFinder { private String sqlServerId; private String name; diff --git a/src/main/java/gyro/azure/sql/SqlFirewallRuleResource.java b/src/main/java/gyro/azure/sql/SqlFirewallRuleResource.java index 1b6c9208..a758102d 100644 --- a/src/main/java/gyro/azure/sql/SqlFirewallRuleResource.java +++ b/src/main/java/gyro/azure/sql/SqlFirewallRuleResource.java @@ -129,7 +129,7 @@ public void copyFrom(SqlFirewallRule firewallRule) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); SqlFirewallRule firewallRule = getSqlFirewallRule(client); @@ -154,7 +154,7 @@ public void create(GyroUI ui, State state) { throw new GyroException("You must provide a sql server resource."); } - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); SqlFirewallRuleOperations.DefinitionStages.WithIpAddressRange rule = client.sqlServers() .getById(getSqlServer().getId()) @@ -175,7 +175,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); SqlFirewallRule.Update update = getSqlFirewallRule(client).update(); @@ -190,7 +190,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); SqlFirewallRule sqlFirewallRule = getSqlFirewallRule(client); diff --git a/src/main/java/gyro/azure/sql/SqlServerFinder.java b/src/main/java/gyro/azure/sql/SqlServerFinder.java index ee862bf9..fa8fe383 100644 --- a/src/main/java/gyro/azure/sql/SqlServerFinder.java +++ b/src/main/java/gyro/azure/sql/SqlServerFinder.java @@ -23,7 +23,7 @@ import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.sql.models.SqlServer; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.Type; /** @@ -37,7 +37,7 @@ * sql-server: $(external-query azure::sql-server {}) */ @Type("sql-server") -public class SqlServerFinder extends AzureResourceManagerFinder { +public class SqlServerFinder extends AzureFinder { private String id; diff --git a/src/main/java/gyro/azure/sql/SqlServerResource.java b/src/main/java/gyro/azure/sql/SqlServerResource.java index 5b5e05d2..7527cc5d 100644 --- a/src/main/java/gyro/azure/sql/SqlServerResource.java +++ b/src/main/java/gyro/azure/sql/SqlServerResource.java @@ -202,7 +202,7 @@ public void copyFrom(SqlServer sqlServer) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); SqlServer sqlServer = client.sqlServers().getById(getId()); @@ -217,7 +217,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); SqlServer.DefinitionStages.WithCreate withCreate = client.sqlServers().define(getName()) .withRegion(Region.fromName(getRegion())) @@ -242,7 +242,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); SqlServer.Update update = client.sqlServers().getById(getId()).update(); @@ -257,7 +257,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.sqlServers().deleteById(getId()); } diff --git a/src/main/java/gyro/azure/sql/SqlVirtualNetworkRuleFinder.java b/src/main/java/gyro/azure/sql/SqlVirtualNetworkRuleFinder.java index dc616095..56435f74 100644 --- a/src/main/java/gyro/azure/sql/SqlVirtualNetworkRuleFinder.java +++ b/src/main/java/gyro/azure/sql/SqlVirtualNetworkRuleFinder.java @@ -25,7 +25,7 @@ import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.sql.models.SqlServer; import com.azure.resourcemanager.sql.models.SqlVirtualNetworkRule; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.Type; /** @@ -40,7 +40,7 @@ */ @Type("sql-virtual-network-rule") public class SqlVirtualNetworkRuleFinder - extends AzureResourceManagerFinder { + extends AzureFinder { private String sqlServerId; private String name; diff --git a/src/main/java/gyro/azure/sql/SqlVirtualNetworkRuleResource.java b/src/main/java/gyro/azure/sql/SqlVirtualNetworkRuleResource.java index 1591093d..09558268 100644 --- a/src/main/java/gyro/azure/sql/SqlVirtualNetworkRuleResource.java +++ b/src/main/java/gyro/azure/sql/SqlVirtualNetworkRuleResource.java @@ -131,7 +131,7 @@ public void copyFrom(SqlVirtualNetworkRule virtualNetworkRule) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); SqlVirtualNetworkRule virtualNetworkRule = getVirtualNetworkRule(client); @@ -150,7 +150,7 @@ public void create(GyroUI ui, State state) { throw new GyroException("You must provide a sql server resource."); } - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); SqlVirtualNetworkRuleOperations.DefinitionStages.WithServiceEndpoint withServiceEndpoint = client.sqlServers() .getById(getSqlServer().getId()) @@ -165,7 +165,7 @@ public void create(GyroUI ui, State state) { @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); SqlVirtualNetworkRule.Update update = getVirtualNetworkRule(client) .update() @@ -176,7 +176,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); SqlVirtualNetworkRule virtualNetworkRule = getVirtualNetworkRule(client); if (virtualNetworkRule != null) { diff --git a/src/main/java/gyro/azure/storage/StorageAccountFinder.java b/src/main/java/gyro/azure/storage/StorageAccountFinder.java index 0349dc40..f406e694 100644 --- a/src/main/java/gyro/azure/storage/StorageAccountFinder.java +++ b/src/main/java/gyro/azure/storage/StorageAccountFinder.java @@ -23,12 +23,12 @@ import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.storage.models.StorageAccount; -import gyro.azure.AzureResourceManagerFinder; +import gyro.azure.AzureFinder; import gyro.core.GyroException; import gyro.core.Type; @Type("storage-account") -public class StorageAccountFinder extends AzureResourceManagerFinder { +public class StorageAccountFinder extends AzureFinder { private String id; private String resourceGroup; diff --git a/src/main/java/gyro/azure/storage/StorageAccountResource.java b/src/main/java/gyro/azure/storage/StorageAccountResource.java index f76e2a68..6eebb73b 100644 --- a/src/main/java/gyro/azure/storage/StorageAccountResource.java +++ b/src/main/java/gyro/azure/storage/StorageAccountResource.java @@ -218,7 +218,7 @@ public void copyFrom(StorageAccount storageAccount) { @Override public boolean refresh() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); StorageAccount storageAccount = client.storageAccounts() .getByResourceGroup(getResourceGroup().getName(), getName()); @@ -234,7 +234,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) throws URISyntaxException, InvalidKeyException { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); StorageAccount.DefinitionStages.WithCreate withCreate = client.storageAccounts() .define(getName()) @@ -256,7 +256,7 @@ public void create(GyroUI ui, State state) throws URISyntaxException, InvalidKey @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) throws URISyntaxException, InvalidKeyException { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); StorageAccount storageAccount = client.storageAccounts().getById(getId()); StorageAccount.Update update = storageAccount.update(); @@ -276,7 +276,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); client.storageAccounts().deleteById(getId()); } @@ -292,7 +292,7 @@ public Map keys() { Map keys = new HashMap<>(); if (getId() != null) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); StorageAccount storageAccount = client.storageAccounts().getById(getId()); storageAccount.getKeys().forEach(e -> keys.put(e.keyName(), e.value())); @@ -302,7 +302,7 @@ public Map keys() { } protected StorageAccount getStorageAccount() { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); return client.storageAccounts().getById(getId()); } diff --git a/src/main/java/gyro/azure/storage/StorageLifeCycle.java b/src/main/java/gyro/azure/storage/StorageLifeCycle.java index 7e158d64..8d9c73fe 100644 --- a/src/main/java/gyro/azure/storage/StorageLifeCycle.java +++ b/src/main/java/gyro/azure/storage/StorageLifeCycle.java @@ -131,7 +131,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) throws Exception { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); StorageAccountResource parent = (StorageAccountResource) parent(); @@ -190,7 +190,7 @@ public void create(GyroUI ui, State state) throws Exception { @Override public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); ManagementPolicySchema policySchema = new ManagementPolicySchema(); policySchema.withRules(getRule().stream().map(PolicyRule::toManagementPolicyRule).collect(Collectors.toList())); @@ -203,7 +203,7 @@ public void update(GyroUI ui, State state, Resource current, Set changed @Override public void delete(GyroUI ui, State state) { - AzureResourceManager client = createResourceManagerClient(); + AzureResourceManager client = createClient(); StorageAccountResource parent = (StorageAccountResource) parent(); StorageAccount storageAccount = client.storageAccounts().getById(parent.getId()); From f0ef1afbae6af1887f0a2901b535450adc41f30c Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Fri, 3 Jun 2022 19:05:50 -0400 Subject: [PATCH 38/43] update build.gradle remove old api reference --- build.gradle | 17 ++++------------- 1 file changed, 4 insertions(+), 13 deletions(-) diff --git a/build.gradle b/build.gradle index 1d1e4e26..f97c7f99 100644 --- a/build.gradle +++ b/build.gradle @@ -65,16 +65,7 @@ dependencies { api 'gyro:gyro-core:1.1.2' implementation 'com.psddev:dari-util:3.3.607-xe0f27a' - implementation 'com.google.guava:guava:23.0' - implementation 'com.microsoft.azure:adal4j:1.6.3' - implementation "com.microsoft.azure:azure:${azureSdkVersion}" - implementation "com.microsoft.azure:azure-mgmt-resources:${azureSdkVersion}" - implementation "com.microsoft.azure:azure-mgmt-network:${azureSdkVersion}" - implementation "com.microsoft.azure:azure-mgmt-compute:${azureSdkVersion}" - implementation "com.microsoft.azure:azure-mgmt-dns:${azureSdkVersion}" - implementation "com.microsoft.azure:azure-mgmt-storage:${azureSdkVersion}" - implementation 'com.github.seancfoley:ipaddress:5.0.2' - implementation 'org.reflections:reflections:0.9.10' + implementation 'com.google.guava:guava:31.1-jre' implementation 'com.azure.resourcemanager:azure-resourcemanager:2.14.0' implementation 'com.azure:azure-security-keyvault-certificates:4.3.2' @@ -82,10 +73,10 @@ dependencies { implementation 'com.azure:azure-storage-queue:12.12.2' implementation 'com.azure:azure-storage-file-share:12.12.2' implementation 'com.azure:azure-storage-blob:12.16.1' - implementation 'com.azure:azure-identity:1.5.0' - implementation 'com.azure:azure-core-http-okhttp:1.8.0' - runtimeOnly 'com.nimbusds:oauth2-oidc-sdk:9.34' implementation 'com.azure:azure-security-keyvault-certificates:4.3.2' + implementation 'com.azure:azure-identity:1.5.1' + implementation 'com.azure:azure-core-http-okhttp:1.9.0' + runtimeOnly 'com.nimbusds:oauth2-oidc-sdk:9.35' gyroDoclet 'gyro:gyro-doclet:1.0.0' } From ed387d38ffa577e7f921ac9c3367641175e90d11 Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Fri, 3 Jun 2022 19:17:46 -0400 Subject: [PATCH 39/43] fix client creation typo --- src/main/java/gyro/azure/AzureCredentials.java | 2 +- src/main/java/gyro/azure/AzureResource.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/gyro/azure/AzureCredentials.java b/src/main/java/gyro/azure/AzureCredentials.java index d7ff99ae..eba2bec2 100644 --- a/src/main/java/gyro/azure/AzureCredentials.java +++ b/src/main/java/gyro/azure/AzureCredentials.java @@ -60,7 +60,7 @@ public void setLogLevel(String logLevel) { this.logLevel = logLevel; } - public AzureResourceManager crateClient() { + public AzureResourceManager createClient() { Properties properties; try (InputStream input = openInput(getCredentialFilePath())) { diff --git a/src/main/java/gyro/azure/AzureResource.java b/src/main/java/gyro/azure/AzureResource.java index b2f8e362..e7f105af 100644 --- a/src/main/java/gyro/azure/AzureResource.java +++ b/src/main/java/gyro/azure/AzureResource.java @@ -27,7 +27,7 @@ protected String getRegion() { } public static AzureResourceManager createClient(AzureCredentials credentials) { - return credentials.crateClient(); + return credentials.createClient(); } protected AzureResourceManager createClient() { From 2603c1b34a1f959b5bf91ee1a3f691fb0b561c9a Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Fri, 17 Jun 2022 10:54:31 -0400 Subject: [PATCH 40/43] fix role assignment --- .../ActiveDirectoryUserResource.java | 2 +- .../RoleAssignmentResource.java | 83 +++++++++++++------ 2 files changed, 59 insertions(+), 26 deletions(-) diff --git a/src/main/java/gyro/azure/accessmanagement/ActiveDirectoryUserResource.java b/src/main/java/gyro/azure/accessmanagement/ActiveDirectoryUserResource.java index dadc79d4..e4aa8957 100644 --- a/src/main/java/gyro/azure/accessmanagement/ActiveDirectoryUserResource.java +++ b/src/main/java/gyro/azure/accessmanagement/ActiveDirectoryUserResource.java @@ -133,8 +133,8 @@ public void setId(String id) { @Override public void copyFrom(ActiveDirectoryUser user) { setName(user.name()); - setEmail(user.innerModel().mailNickname()); setPrincipalName(user.userPrincipalName()); + setEmail(getPrincipalName().split("@")[0]); setId(user.id()); setAccountEnabled(user.innerModel().accountEnabled()); } diff --git a/src/main/java/gyro/azure/accessmanagement/RoleAssignmentResource.java b/src/main/java/gyro/azure/accessmanagement/RoleAssignmentResource.java index 01867c79..cc3706b1 100644 --- a/src/main/java/gyro/azure/accessmanagement/RoleAssignmentResource.java +++ b/src/main/java/gyro/azure/accessmanagement/RoleAssignmentResource.java @@ -19,9 +19,11 @@ import java.util.Objects; import java.util.Set; import java.util.UUID; +import java.util.concurrent.TimeUnit; import java.util.stream.Stream; import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.authorization.fluent.models.OdataErrorMainException; import com.azure.resourcemanager.authorization.models.ActiveDirectoryGroup; import com.azure.resourcemanager.authorization.models.ActiveDirectoryUser; import com.azure.resourcemanager.authorization.models.BuiltInRole; @@ -31,6 +33,7 @@ import gyro.core.GyroException; import gyro.core.GyroUI; import gyro.core.Type; +import gyro.core.Wait; import gyro.core.resource.Output; import gyro.core.resource.Resource; import gyro.core.scope.State; @@ -152,15 +155,26 @@ public void copyFrom(RoleAssignment roleAssignment) { AzureResourceManager client = createClient(); setRole(client.accessManagement().roleDefinitions().getById(roleAssignment.roleDefinitionId()).roleName()); - ActiveDirectoryUser user = client.accessManagement().activeDirectoryUsers().getById(getPrincipalId()); - ActiveDirectoryGroup group = client.accessManagement().activeDirectoryGroups().getById(getPrincipalId()); + ActiveDirectoryUser user = null; + + try { + user = client.accessManagement().activeDirectoryUsers().getById(getPrincipalId()); + } catch (OdataErrorMainException ex) { + // ignore + } + + ActiveDirectoryGroup group = null; + + try { + group = client.accessManagement().activeDirectoryGroups().getById(getPrincipalId()); + } catch (OdataErrorMainException ex) { + //ignore + } if (user != null) { setUser(findById(ActiveDirectoryUserResource.class, user.id())); - setPrincipalId(null); } else if (group != null) { setGroup(findById(ActiveDirectoryGroupResource.class, getPrincipalId())); - setPrincipalId(null); } } @@ -188,27 +202,46 @@ public void create(GyroUI ui, State state) throws Exception { } RoleAssignment roleAssignment = null; - - if (getPrincipalId() != null) { - roleAssignment = client.accessManagement().roleAssignments().define(UUID.randomUUID().toString()) - .forObjectId(getPrincipalId()) - .withBuiltInRole(BuiltInRole.fromString(getRole())) - .withScope(getScope()) - .create(); - } else if (getGroup() != null) { - roleAssignment = client.accessManagement().roleAssignments().define(UUID.randomUUID().toString()) - .forGroup(client.accessManagement().activeDirectoryGroups().getById(getGroup().getId())) - .withBuiltInRole(BuiltInRole.fromString(getRole())) - .withScope(getScope()) - .create(); - } else if (getUser() != null) { - roleAssignment = client.accessManagement().roleAssignments().define(UUID.randomUUID().toString()) - .forUser(client.accessManagement().activeDirectoryUsers().getById(getUser().getId())) - .withBuiltInRole(BuiltInRole.fromString(getRole())) - .withScope(getScope()) - .create(); - } else { - throw new GyroException("One of 'principal-id' or 'user' or 'group' is required."); + setName(UUID.randomUUID().toString()); + + try { + if (getPrincipalId() != null) { + roleAssignment = client.accessManagement().roleAssignments().define(getName()) + .forObjectId(getPrincipalId()) + .withBuiltInRole(BuiltInRole.fromString(getRole())) + .withScope(getScope()) + .create(); + } else if (getGroup() != null) { + roleAssignment = client.accessManagement().roleAssignments().define(getName()) + .forGroup(client.accessManagement().activeDirectoryGroups().getById(getGroup().getId())) + .withBuiltInRole(BuiltInRole.fromString(getRole())) + .withScope(getScope()) + .create(); + } else if (getUser() != null) { + roleAssignment = client.accessManagement().roleAssignments().define(getName()) + .forUser(client.accessManagement().activeDirectoryUsers().getById(getUser().getId())) + .withBuiltInRole(BuiltInRole.fromString(getRole())) + .withScope(getScope()) + .create(); + } else { + throw new GyroException("One of 'principal-id' or 'user' or 'group' is required."); + } + } catch (OdataErrorMainException ex) { + + try { + Wait.atMost(2, TimeUnit.MINUTES) + .prompt(false) + .checkEvery(20, TimeUnit.SECONDS) + .until(() -> client.accessManagement().roleAssignments().getByScope(getScope(), getName()) != null); + + roleAssignment = client.accessManagement().roleAssignments().getByScope(getScope(), getName()); + + if (roleAssignment == null) { + throw ex; + } + } catch (Exception exx) { + throw ex; + } } copyFrom(roleAssignment); From 34b81dfcb53b81dfbdc964f6264985220322b1ad Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Fri, 24 Jun 2022 13:50:49 -0400 Subject: [PATCH 41/43] Update DnsZoneResource.java --- .../java/gyro/azure/dns/DnsZoneResource.java | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/src/main/java/gyro/azure/dns/DnsZoneResource.java b/src/main/java/gyro/azure/dns/DnsZoneResource.java index d423aaa5..b8a8aeab 100644 --- a/src/main/java/gyro/azure/dns/DnsZoneResource.java +++ b/src/main/java/gyro/azure/dns/DnsZoneResource.java @@ -64,7 +64,7 @@ public class DnsZoneResource extends AzureResource implements Copyable private Map tags; private List nsRecords; - private Map> nameServers; + private List nameServers; /** * The ID of the Dns Zone. @@ -136,18 +136,18 @@ public void setNsRecords(List nsRecords) { } /** - * A map of ns record names and corresponding name servers present in the Dns Zone. + * A list of name servers present in the Dns Zone. */ @Output - public Map> getNameServers() { + public List getNameServers() { if (nameServers == null) { - nameServers = new HashMap<>(); + nameServers = new ArrayList<>(); } return nameServers; } - public void setNameServers(Map> nameServers) { + public void setNameServers(List nameServers) { this.nameServers = nameServers; } @@ -162,8 +162,7 @@ public void copyFrom(DnsZone dnsZone) { .map(HasName::name) .collect(Collectors.toList())); - setNameServers(dnsZone.nsRecordSets().list().stream() - .collect(Collectors.toMap(HasName::name, NsRecordSet::nameServers))); + setNameServers(dnsZone.nameServers()); } @Override @@ -195,7 +194,9 @@ public void create(GyroUI ui, State state) { DnsZone dnsZone = withCreate.create(); - copyFrom(dnsZone); + setId(dnsZone.id()); + + copyFrom(client.dnsZones().getById(getId())); } @Override From 98ae2faaf03276b3f46f236972bf82a9e360f3d3 Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Tue, 12 Jul 2022 08:54:06 -0700 Subject: [PATCH 42/43] more keyvault refactor --- build.gradle | 2 +- examples/keyvault/certificate.gyro | 53 ++++++++----------- .../keyvault/KeyVaultCertificatePolicy.java | 19 +++++-- .../keyvault/KeyVaultCertificateResource.java | 5 +- .../azure/keyvault/KeyVaultKeyAttribute.java | 4 +- .../azure/keyvault/KeyVaultKeyResource.java | 4 +- .../gyro/azure/keyvault/KeyVaultResource.java | 8 +-- .../keyvault/KeyVaultSecretAttribute.java | 4 +- 8 files changed, 51 insertions(+), 48 deletions(-) diff --git a/build.gradle b/build.gradle index f97c7f99..a313dd6e 100644 --- a/build.gradle +++ b/build.gradle @@ -67,7 +67,7 @@ dependencies { implementation 'com.psddev:dari-util:3.3.607-xe0f27a' implementation 'com.google.guava:guava:31.1-jre' - implementation 'com.azure.resourcemanager:azure-resourcemanager:2.14.0' + implementation 'com.azure.resourcemanager:azure-resourcemanager:2.15.0' implementation 'com.azure:azure-security-keyvault-certificates:4.3.2' implementation 'com.azure:azure-data-tables:12.3.0' implementation 'com.azure:azure-storage-queue:12.12.2' diff --git a/examples/keyvault/certificate.gyro b/examples/keyvault/certificate.gyro index 1bbc4b91..d8a1be62 100644 --- a/examples/keyvault/certificate.gyro +++ b/examples/keyvault/certificate.gyro @@ -38,41 +38,30 @@ azure::key-vault-certificate vault-certificate-example vault: $(azure::key-vault vault-example-certificate) policy - key-properties - exportable: false - reuse-key: false - #size: 2048 - #type: "RSA" - end + certificate-type: "" + content-type: "application/x-pkcs12" + transparent: false + key-curve-name: "P-256" + key-size: 2048 + validity-in-months: 2 + enabled: false + enhanced-key-usage: [] + exportable: false + key-reusable: false + key-usage: ["digitalSignature", "keyEncipherment"] + key-type: "RSA" + subject: "CN=a1.com" lifetime-action - action - type: "EmailContacts" - end - - trigger - lifetime-percentage: 90 - end + action: "EmailContacts" + days-before-expiring: 356 + lifetime-percentage: 90 end - secret-properties - content-type: "application/x-pkcs12" - end - - x509-properties - key-usage: ["digitalSignature", "keyEncipherment"] - subject: "CN=a1.com" - validity-in-months: 2 - ekus: ["1.3.6.1.5.5.7.3.1", "1.3.6.1.5.5.7.3.2"] - end - - attribute - "enabled" : true - "expires" : "2020-04-03T15:54:12.000Z" - end - - issuer-parameter - name: "Self" + subject-alternative-name + email: [""] + dns-names: [""] + upns: [""] end end -end \ No newline at end of file +end diff --git a/src/main/java/gyro/azure/keyvault/KeyVaultCertificatePolicy.java b/src/main/java/gyro/azure/keyvault/KeyVaultCertificatePolicy.java index 48f690c7..6f8008d0 100644 --- a/src/main/java/gyro/azure/keyvault/KeyVaultCertificatePolicy.java +++ b/src/main/java/gyro/azure/keyvault/KeyVaultCertificatePolicy.java @@ -108,9 +108,9 @@ public void setSubject(String subject) { } /** - * The key type. Currently only supported value is ``RSA``. + * The key type. */ - @ValidStrings("RSA") + @ValidStrings({"RSA", "RSA-HSM", "EC", "EC-HSM"}) public String getKeyType() { return keyType; } @@ -119,6 +119,10 @@ public void setKeyType(String keyType) { this.keyType = keyType; } + /** + * The key curve name. + */ + @ValidStrings({"P-256", "P-384", "P-521", "P-256K"}) public String getKeyCurveName() { return keyCurveName; } @@ -138,6 +142,9 @@ public void setEnabled(Boolean enabled) { this.enabled = enabled; } + /** + * Enable or Disable transparency of the certificate. + */ public Boolean getTransparent() { return transparent; } @@ -171,7 +178,7 @@ public void setKeyReusable(Boolean keyReusable) { } /** - * Validation of the certificate in months. Value should be between 1 to 12. + * Validation of the certificate in months. */ @Required @Range(min = 1, max = 12) @@ -235,6 +242,9 @@ public void setSubjectAlternativeName(KeyVaultCertificateSubjectAlternativeName /** * A list of key usage flags. */ + @ValidStrings({"digitalSignature", "nonRepudiation", "keyEncipherment", + "dataEncipherment", "keyAgreement", "keyCertSign", + "cRLSign", "encipherOnly", "decipherOnly"}) public List getKeyUsage() { if (keyUsage == null) { keyUsage = new ArrayList<>(); @@ -247,6 +257,9 @@ public void setKeyUsage(List keyUsage) { this.keyUsage = keyUsage; } + /** + * A list of enhanced key usage flags. + */ public List getEnhancedKeyUsage() { if (enhancedKeyUsage == null) { enhancedKeyUsage = new ArrayList<>(); diff --git a/src/main/java/gyro/azure/keyvault/KeyVaultCertificateResource.java b/src/main/java/gyro/azure/keyvault/KeyVaultCertificateResource.java index c5892b15..ecf8dacd 100644 --- a/src/main/java/gyro/azure/keyvault/KeyVaultCertificateResource.java +++ b/src/main/java/gyro/azure/keyvault/KeyVaultCertificateResource.java @@ -41,7 +41,6 @@ import gyro.core.resource.Updatable; import gyro.core.scope.State; import gyro.core.validation.Required; -import org.jetbrains.annotations.NotNull; /** * Creates a key vault certificate. @@ -268,7 +267,8 @@ public void create(GyroUI ui, State state) throws Exception { if (getPolicy().getIssuerName().equals("Unknown")) { GyroCore.ui() .write( - "\n@|blue Certificate created, but needs to be merged before use. Please use the Azure console to merge the certificate! |@\n\n"); + "\n@|blue Certificate created, but needs to be merged before use. " + + "Please use the Azure console to merge the certificate! |@\n\n"); } } } @@ -289,6 +289,7 @@ public void delete(GyroUI ui, State state) throws Exception { syncPoller.getFinalResult(); } catch (IllegalArgumentException ex) { // Do something + // TODO verify certificate exception, also affect finders and command } } diff --git a/src/main/java/gyro/azure/keyvault/KeyVaultKeyAttribute.java b/src/main/java/gyro/azure/keyvault/KeyVaultKeyAttribute.java index dd4d5bd4..7e032694 100644 --- a/src/main/java/gyro/azure/keyvault/KeyVaultKeyAttribute.java +++ b/src/main/java/gyro/azure/keyvault/KeyVaultKeyAttribute.java @@ -31,7 +31,7 @@ public void setEnabled(Boolean enabled) { } /** - * A date time value value in UTC specifying when the key expires. Format ``YYYY-MM-DDTHH:MM:SS.sssZ``. Example ``2020-04-03T15:54:12.000Z``. + * A date time value in UTC specifying when the key expires. Format ``YYYY-MM-DDTHH:MM:SS.sssZ``. Example ``2020-04-03T15:54:12.000Z``. */ @Updatable public String getExpires() { @@ -43,7 +43,7 @@ public void setExpires(String expires) { } /** - * A date time value value in UTC specifying the not before time. Format ``YYYY-MM-DDTHH:MM:SS.sssZ``. Example ``2020-04-03T15:54:12.000Z``. + * A date time value in UTC specifying the not-before time. Format ``YYYY-MM-DDTHH:MM:SS.sssZ``. Example ``2020-04-03T15:54:12.000Z``. */ @Updatable public String getNotBefore() { diff --git a/src/main/java/gyro/azure/keyvault/KeyVaultKeyResource.java b/src/main/java/gyro/azure/keyvault/KeyVaultKeyResource.java index 4a393fc5..d4967809 100644 --- a/src/main/java/gyro/azure/keyvault/KeyVaultKeyResource.java +++ b/src/main/java/gyro/azure/keyvault/KeyVaultKeyResource.java @@ -91,7 +91,7 @@ public void setVault(KeyVaultResource vault) { * The type of the key. Valid values are ``EC``, ``RSA``, ``RSA-HSM`` or ``oct`` */ @Required - @ValidStrings({"EC", "RSA", "RSA-HSM", "oct"}) + @ValidStrings({"EC", "EC-HSM", "RSA", "RSA-HSM", "OCT", "OCT-HSM"}) public String getType() { return type; } @@ -130,7 +130,7 @@ public void setSize(Integer size) { * A set of key operations that you want to enable. */ @Updatable - @ValidStrings({"encrypt", "decrypt", "sign", "verify", "wrapKey", "unwrapKey"}) + @ValidStrings({"encrypt", "decrypt", "sign", "verify", "wrapKey", "unwrapKey", "import"}) public List getOperations() { if (operations == null) { operations = new ArrayList<>(); diff --git a/src/main/java/gyro/azure/keyvault/KeyVaultResource.java b/src/main/java/gyro/azure/keyvault/KeyVaultResource.java index ed066dc2..39f58f7d 100644 --- a/src/main/java/gyro/azure/keyvault/KeyVaultResource.java +++ b/src/main/java/gyro/azure/keyvault/KeyVaultResource.java @@ -245,7 +245,7 @@ public void setAccessPolicy(Set accessPolicy) { } /** - * When ``true`` virtual machines are permitted to retrieve certificates stored as secrets from the key vault. + * When set to``true`` virtual machines are permitted to retrieve certificates stored as secrets from the key vault. */ @Updatable public Boolean getEnableDeployment() { @@ -261,7 +261,7 @@ public void setEnableDeployment(Boolean enableDeployment) { } /** - * When ``true`` resource managers are permitted to retrieve certificates stored as secrets from the key vault. + * When set to ``true`` resource managers are permitted to retrieve certificates stored as secrets from the key vault. */ @Updatable public Boolean getEnableTemplateDeployment() { @@ -277,7 +277,7 @@ public void setEnableTemplateDeployment(Boolean enableTemplateDeployment) { } /** - * When ``true`` disk managers are permitted to retrieve certificates stored as secrets from the key vault and unwrap keys. + * When set to ``true`` disk managers are permitted to retrieve certificates stored as secrets from the key vault and unwrap keys. */ @Updatable public Boolean getEnableDiskEncryption() { @@ -309,7 +309,7 @@ public void setEnablePurgeVault(Boolean enablePurgeVault) { } /** - * Enables soft delete for the key vault. + * When set to ``true`` enables soft delete for the key vault. */ @Updatable public Boolean getEnableSoftDelete() { diff --git a/src/main/java/gyro/azure/keyvault/KeyVaultSecretAttribute.java b/src/main/java/gyro/azure/keyvault/KeyVaultSecretAttribute.java index fe06410d..0f4efd53 100644 --- a/src/main/java/gyro/azure/keyvault/KeyVaultSecretAttribute.java +++ b/src/main/java/gyro/azure/keyvault/KeyVaultSecretAttribute.java @@ -30,7 +30,7 @@ public void setEnabled(Boolean enabled) { } /** - * A date time value value in UTC specifying when the secret expires. Format ``YYYY-MM-DDTHH:MM:SS.sssZ``. Example ``2020-04-03T15:54:12.000Z``. + * A date time value in UTC specifying when the secret expires. Format ``YYYY-MM-DDTHH:MM:SS.sssZ``. Example ``2020-04-03T15:54:12.000Z``. */ @Updatable public String getExpires() { @@ -42,7 +42,7 @@ public void setExpires(String expires) { } /** - * A date time value value in UTC specifying the not before time. Format ``YYYY-MM-DDTHH:MM:SS.sssZ``. Example ``2020-04-03T15:54:12.000Z``. + * A date time value in UTC specifying the not-before time. Format ``YYYY-MM-DDTHH:MM:SS.sssZ``. Example ``2020-04-03T15:54:12.000Z``. */ @Updatable public String getNotBefore() { From cbf2fa5889139160f3a29632868a03e9fed5b333 Mon Sep 17 00:00:00 2001 From: Deepanjan Bhattacharyya Date: Tue, 12 Jul 2022 08:55:33 -0700 Subject: [PATCH 43/43] storage lifecycle refactor --- .../java/gyro/azure/storage/PolicyFilter.java | 4 +++- .../java/gyro/azure/storage/PolicyRule.java | 23 ++++++++++--------- .../gyro/azure/storage/StorageLifeCycle.java | 10 ++++---- 3 files changed, 21 insertions(+), 16 deletions(-) diff --git a/src/main/java/gyro/azure/storage/PolicyFilter.java b/src/main/java/gyro/azure/storage/PolicyFilter.java index 0a8b012b..6f3432e4 100644 --- a/src/main/java/gyro/azure/storage/PolicyFilter.java +++ b/src/main/java/gyro/azure/storage/PolicyFilter.java @@ -24,6 +24,7 @@ import gyro.azure.Copyable; import gyro.core.resource.Diffable; import gyro.core.resource.Updatable; +import gyro.core.validation.ValidStrings; public class PolicyFilter extends Diffable implements Copyable { @@ -31,8 +32,9 @@ public class PolicyFilter extends Diffable implements Copyable prefixMatches; /** - * Allowed blob types for the filter. Currently only supported value is ``blockBlob``. Defaults to ``blockBlob``. + * Allowed blob types for the filter. Defaults to ``blockBlob``. */ + @ValidStrings({"blockBlob", "appendBlob"}) public Set getBlobTypes() { if (blobTypes == null) { blobTypes = new HashSet<>(); diff --git a/src/main/java/gyro/azure/storage/PolicyRule.java b/src/main/java/gyro/azure/storage/PolicyRule.java index 0981e89c..2a48481d 100644 --- a/src/main/java/gyro/azure/storage/PolicyRule.java +++ b/src/main/java/gyro/azure/storage/PolicyRule.java @@ -22,11 +22,12 @@ import gyro.core.resource.Diffable; import gyro.core.resource.Updatable; import gyro.core.validation.Required; +import gyro.core.validation.ValidStrings; public class PolicyRule extends Diffable implements Copyable { private String name; - private RuleType type; + private String type; private Boolean enabled; private PolicyDefinition definition; @@ -43,17 +44,18 @@ public void setName(String name) { } /** - * Type of rule. Currently only supported value is ``Lifecycle``. Defaults to ``Lifecycle``. + * Type of rule. */ - public RuleType getType() { + @ValidStrings("Lifecycle") + public String getType() { if (type == null) { - type = RuleType.LIFECYCLE; + type = RuleType.LIFECYCLE.toString(); } return type; } - public void setType(RuleType type) { + public void setType(String type) { this.type = type; } @@ -76,7 +78,7 @@ public void setEnabled(Boolean enabled) { /** * The rule details. * - * @sunresource gyro.azure.storage.PolicyDefinition + * @subresource gyro.azure.storage.PolicyDefinition */ @Required @Updatable @@ -96,7 +98,7 @@ public String primaryKey() { @Override public void copyFrom(ManagementPolicyRule rule) { setName(rule.name()); - setType(rule.type()); + setType(rule.type().toString()); setEnabled(rule.enabled()); PolicyDefinition policyDefinition = newSubresource(PolicyDefinition.class); policyDefinition.copyFrom(rule.definition()); @@ -105,11 +107,10 @@ public void copyFrom(ManagementPolicyRule rule) { ManagementPolicyRule toManagementPolicyRule() { ManagementPolicyRule rule = new ManagementPolicyRule(); - rule = rule.withName(getName()) - .withType(getType()) + + return rule.withName(getName()) + .withType(RuleType.fromString(getType())) .withEnabled(getEnabled()) .withDefinition(getDefinition().toManagementPolicyDefinition()); - - return rule; } } diff --git a/src/main/java/gyro/azure/storage/StorageLifeCycle.java b/src/main/java/gyro/azure/storage/StorageLifeCycle.java index 8d9c73fe..1040df37 100644 --- a/src/main/java/gyro/azure/storage/StorageLifeCycle.java +++ b/src/main/java/gyro/azure/storage/StorageLifeCycle.java @@ -27,6 +27,8 @@ import com.azure.resourcemanager.storage.models.ManagementPolicy; import com.azure.resourcemanager.storage.models.ManagementPolicyRule; import com.azure.resourcemanager.storage.models.ManagementPolicySchema; +import com.azure.resourcemanager.storage.models.PolicyRule.DefinitionStages.WithBlobTypesToFilterFor; +import com.azure.resourcemanager.storage.models.PolicyRule.DefinitionStages.WithPolicyRuleAttachable; import com.azure.resourcemanager.storage.models.StorageAccount; import gyro.azure.AzureResource; import gyro.azure.Copyable; @@ -47,7 +49,7 @@ public class StorageLifeCycle extends AzureResource implements Copyable rule; /** - * The name of the lifecycle policy. Currently only supported value is ``DefaultManagementPolicy``. Defaults to ``DefaultManagementPolicy``. + * The name of the lifecycle policy. */ @ValidStrings("DefaultManagementPolicy") public String getName() { @@ -150,12 +152,12 @@ public void create(GyroUI ui, State state) throws Exception { ManagementPolicy.DefinitionStages.WithCreate create = null; for (PolicyRule rule : getRule()) { - com.azure.resourcemanager.storage.models.PolicyRule.DefinitionStages.WithBlobTypesToFilterFor withBlobTypesToFilterFor = + WithBlobTypesToFilterFor withBlobTypesToFilterFor = create == null ? withRule.defineRule(rule.getName()).withLifecycleRuleType() : create.defineRule(rule.getName()).withLifecycleRuleType(); - com.azure.resourcemanager.storage.models.PolicyRule.DefinitionStages.WithPolicyRuleAttachable withPolicyRuleAttachable = withBlobTypesToFilterFor + WithPolicyRuleAttachable withPolicyRuleAttachable = withBlobTypesToFilterFor .withBlobTypesToFilterFor(rule.getDefinition() .getFilter() .getBlobTypes() @@ -180,7 +182,7 @@ public void create(GyroUI ui, State state) throws Exception { state.save(); // Api does not allow creating one or more disabled rule when creating a policy. - // If one or more rules are are configured to be disabled then an update is required. + // If one or more rules are configured to be disabled then an update is required. if (getRule().stream().anyMatch(o -> !o.getEnabled())) { update(ui, state, this, new HashSet<>()); } else {