diff --git a/build.gradle b/build.gradle index 09470611..af970e26 100644 --- a/build.gradle +++ b/build.gradle @@ -60,24 +60,26 @@ 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: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' - - gyroDoclet 'gyro:gyro-doclet:0.99.1' + implementation 'com.google.guava:guava:31.1-jre' + + 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' + implementation 'com.azure:azure-storage-file-share:12.12.2' + implementation 'com.azure:azure-storage-blob:12.16.1' + 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' } task referenceDocs(type: Javadoc) { 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/examples/accessmanagement/serviceprincipal.gyro b/examples/accessmanagement/serviceprincipal.gyro new file mode 100644 index 00000000..42780e58 --- /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-service-principal-example) +end diff --git a/examples/containerservice/kubernetes-cluster.gyro b/examples/containerservice/kubernetes-cluster.gyro new file mode 100644 index 00000000..0c7dacfa --- /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" + network-plugin: "azure" + + 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/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/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/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/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/examples/storage/cloud-blob-container.gyro b/examples/storage/cloud-blob-container.gyro index 1aec2e20..a8fd55ec 100644 --- a/examples/storage/cloud-blob-container.gyro +++ b/examples/storage/cloud-blob-container.gyro @@ -8,24 +8,19 @@ end 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 + 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/AbstractAzureCommand.java b/src/main/java/gyro/azure/AbstractAzureCommand.java index 29d28dc6..7c2a365a 100644 --- a/src/main/java/gyro/azure/AbstractAzureCommand.java +++ b/src/main/java/gyro/azure/AbstractAzureCommand.java @@ -25,7 +25,8 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -import com.microsoft.azure.management.Azure; +import com.azure.core.credential.TokenCredential; +import com.azure.resourcemanager.AzureResourceManager; import gyro.core.GyroCore; import gyro.core.GyroException; import gyro.core.GyroInputStream; @@ -85,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()); @@ -99,6 +100,20 @@ public Azure getClient() { return AzureResource.createClient((AzureCredentials) credentials); } + public TokenCredential getTokenCredential() { + 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.getTokenCredential((AzureCredentials) credentials); + } + private void evaluateFile(String file, Consumer consumer, RootScope current) { if (StringUtils.isBlank(file)) { return; diff --git a/src/main/java/gyro/azure/AzureCredentials.java b/src/main/java/gyro/azure/AzureCredentials.java index b9a76271..eba2bec2 100644 --- a/src/main/java/gyro/azure/AzureCredentials.java +++ b/src/main/java/gyro/azure/AzureCredentials.java @@ -18,26 +18,17 @@ import java.io.IOException; import java.io.InputStream; -import java.util.Collections; import java.util.Properties; -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.azure.core.credential.TokenCredential; +import com.azure.core.http.okhttp.OkHttpAsyncHttpClientBuilder; +import com.azure.core.management.profile.AzureProfile; +import com.azure.identity.ClientSecretCredentialBuilder; +import com.azure.resourcemanager.AzureResourceManager; 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 { @@ -69,8 +60,7 @@ public void setLogLevel(String logLevel) { this.logLevel = logLevel; } - public Azure createClient() { - AzureEnvironment environment = AzureEnvironment.AZURE; + public AzureResourceManager createClient() { Properties properties; try (InputStream input = openInput(getCredentialFilePath())) { @@ -81,36 +71,56 @@ 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 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())) { + properties = new Properties(); + + properties.load(input); + + } catch (IOException error) { + throw new GyroException(error.getMessage()); + } + + 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 6fb0d5d0..e7f105af 100644 --- a/src/main/java/gyro/azure/AzureResource.java +++ b/src/main/java/gyro/azure/AzureResource.java @@ -16,21 +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) { + protected String getRegion() { + return credentials(AzureCredentials.class).getRegion(); + } + + public static AzureResourceManager createClient(AzureCredentials credentials) { return credentials.createClient(); } - protected Azure createClient() { + protected AzureResourceManager createClient() { return AzureResource.createClient(credentials(AzureCredentials.class)); } - protected String getRegion() { - return credentials(AzureCredentials.class).getRegion(); + public static TokenCredential getTokenCredential(AzureCredentials credentials) { + return credentials.getTokenCredential(); } + protected TokenCredential getTokenCredential() { + return credentials(AzureCredentials.class).getTokenCredential(); + } } diff --git a/src/main/java/gyro/azure/CloudBlobContainerFileBackend.java b/src/main/java/gyro/azure/CloudBlobContainerFileBackend.java deleted file mode 100644 index 98ea2e16..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); - - 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/accessmanagement/ActiveDirectoryGroupFinder.java b/src/main/java/gyro/azure/accessmanagement/ActiveDirectoryGroupFinder.java index 2a1a3c1b..d6755a45 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.AzureFinder; +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 AzureFinder { + 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..58233f12 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 = createClient(); 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 = createClient(); 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 = 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 7631f0e6..b1f05760 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.AzureFinder; +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 AzureFinder { + 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..e4aa8957 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()); setPrincipalName(user.userPrincipalName()); + setEmail(getPrincipalName().split("@")[0]); setId(user.id()); - setAccountEnabled(user.inner().accountEnabled()); + setAccountEnabled(user.innerModel().accountEnabled()); } @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createClient(); 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 = createClient(); 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 = 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 new file mode 100644 index 00000000..00da2c25 --- /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.AzureFinder; +import gyro.core.Type; + +/** + * Query application. + * + * Example + * ------- + * + * .. code-block:: gyro + * + * application: $(external-query azure::application {}) + */ +@Type("application") +public class ApplicationFinder extends AzureFinder { + + 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..3476f98c --- /dev/null +++ b/src/main/java/gyro/azure/accessmanagement/ApplicationResource.java @@ -0,0 +1,265 @@ +/* + * 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 = createClient(); + + 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 = createClient(); + + 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 = createClient(); + + 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 = 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 d889eee4..cc3706b1 100644 --- a/src/main/java/gyro/azure/accessmanagement/RoleAssignmentResource.java +++ b/src/main/java/gyro/azure/accessmanagement/RoleAssignmentResource.java @@ -16,26 +16,29 @@ 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 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; +import com.azure.resourcemanager.authorization.models.RoleAssignment; import gyro.azure.AzureResource; import gyro.azure.Copyable; 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; 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 +55,7 @@ */ @Type("role-assignment") public class RoleAssignmentResource extends AzureResource implements Copyable { + private String name; private String scope; private String role; @@ -148,24 +152,35 @@ public void copyFrom(RoleAssignment roleAssignment) { setScope(roleAssignment.scope()); setId(roleAssignment.id()); - Azure client = createClient(); + 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); } } @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createClient(); RoleAssignment roleAssignment = client.accessManagement().roleAssignments().getByScope(getScope(), getName()); @@ -180,34 +195,53 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) throws Exception { - Azure client = createClient(); + 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."); } 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); @@ -220,7 +254,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 = 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 new file mode 100644 index 00000000..aecdcf0e --- /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.AzureFinder; +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 AzureFinder { + + 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..941cd166 --- /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 = createClient(); + + 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 = createClient(); + + 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 = 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 042b6cb1..7b7161bc 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 = createClient(); 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 = createClient(); 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 = createClient(); 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..0b045561 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.AzureFinder; +import gyro.core.Type; /** * Query cdn profile. @@ -37,6 +38,7 @@ */ @Type("cdn-profile") public class CdnProfileFinder extends AzureFinder { + 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..f908dadb 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 = createClient(); 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 = createClient(); - 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 = createClient(); 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 = createClient(); 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())); 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..08d08c43 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.AzureFinder; +import gyro.core.Type; /** * Query availability set. @@ -37,6 +38,7 @@ */ @Type("availability-set") public class AvailabilitySetFinder extends AzureFinder { + 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..c2712418 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 = createClient(); 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 = createClient(); 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 = createClient(); - 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 = 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 2464b49b..aa7aeb92 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.AzureFinder; +import gyro.core.Type; /** * Query disk. @@ -37,6 +38,7 @@ */ @Type("disk") public class DiskFinder extends AzureFinder { + 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..c40a4a55 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 = createClient(); 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 = createClient(); 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 = createClient(); 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 = createClient(); 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..bf4c04b0 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.AzureFinder; +import gyro.core.Type; /** * Query snapshot. @@ -37,6 +38,7 @@ */ @Type("snapshot") public class SnapshotFinder extends AzureFinder { + 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..a301afb3 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 = createClient(); 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 = createClient(); 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 = createClient(); 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 = 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 cfc20b61..9456e6de 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.AzureFinder; +import gyro.core.Type; /** * Query scale set. @@ -37,6 +38,7 @@ */ @Type("scale-set") public class VMScaleSetFinder extends AzureFinder { + 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..b52fe556 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 = createClient(); 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 = createClient(); + + 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 = createClient(); 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 = createClient(); 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 = createClient(); 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..abcc8f73 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.AzureFinder; +import gyro.core.Type; /** * Query scale set scaling. @@ -37,6 +38,7 @@ */ @Type("scale-set-scaling") public class VMScaleSetScalingFinder extends AzureFinder { + 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..d2436e00 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 = createClient(); 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 = createClient(); 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 = createClient(); 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 = createClient(); 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..d64c7e2c 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.AzureFinder; +import gyro.core.Type; /** * Query virtual machine. @@ -37,6 +38,7 @@ */ @Type("virtual-machine") public class VirtualMachineFinder extends AzureFinder { + 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..3fbc78e5 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.AzureFinder; +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 AzureFinder { + 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..6cfd5570 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 = createClient(); 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 = createClient(); 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 = 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 fc89f536..5b1bc9a5 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 = createClient(); setPrivateIpAddress(client.networkInterfaces().getById(getNetworkInterface().getId()).primaryPrivateIP()); } @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createClient(); VirtualMachine virtualMachine = client.virtualMachines().getById(getId()); @@ -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 = createClient(); 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 = createClient(); 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 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..b4465893 --- /dev/null +++ b/src/main/java/gyro/azure/containerservice/ApiServerAccessProfile.java @@ -0,0 +1,129 @@ +/* + * 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; +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/ClusterAddonProfile.java b/src/main/java/gyro/azure/containerservice/ClusterAddonProfile.java new file mode 100644 index 00000000..f10268a8 --- /dev/null +++ b/src/main/java/gyro/azure/containerservice/ClusterAddonProfile.java @@ -0,0 +1,98 @@ +/* + * 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; +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..155ab1d1 --- /dev/null +++ b/src/main/java/gyro/azure/containerservice/ClusterAgentPool.java @@ -0,0 +1,425 @@ +/* + * 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; +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. + */ + @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..90324030 --- /dev/null +++ b/src/main/java/gyro/azure/containerservice/ClusterLoadBalancerManagedOutboundIps.java @@ -0,0 +1,55 @@ +/* + * 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; +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..5873d1cf --- /dev/null +++ b/src/main/java/gyro/azure/containerservice/ClusterLoadBalancerOutboundIpPrefixes.java @@ -0,0 +1,68 @@ +/* + * 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; +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..2b99b7c0 --- /dev/null +++ b/src/main/java/gyro/azure/containerservice/ClusterLoadBalancerOutboundIps.java @@ -0,0 +1,72 @@ +/* + * 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; +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..f3c5fa8b --- /dev/null +++ b/src/main/java/gyro/azure/containerservice/ClusterLoadBalancerProfile.java @@ -0,0 +1,201 @@ +/* + * 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; +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..3e1dbb2d --- /dev/null +++ b/src/main/java/gyro/azure/containerservice/ClusterManagedOutboundIpProfile.java @@ -0,0 +1,53 @@ +/* + * 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; +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..55536e69 --- /dev/null +++ b/src/main/java/gyro/azure/containerservice/ClusterNatGatewayProfile.java @@ -0,0 +1,118 @@ +/* + * 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; +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..02c833e2 --- /dev/null +++ b/src/main/java/gyro/azure/containerservice/ClusterPropertiesAutoScalerProfile.java @@ -0,0 +1,334 @@ +/* + * 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; +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..ccbfeb09 --- /dev/null +++ b/src/main/java/gyro/azure/containerservice/KubernetesClusterFinder.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.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.AzureFinder; +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 AzureFinder { + + 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..11ff1b1d --- /dev/null +++ b/src/main/java/gyro/azure/containerservice/KubernetesClusterResource.java @@ -0,0 +1,803 @@ +/* + * 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; +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.LoadBalancerSku; +import com.azure.resourcemanager.containerservice.models.ManagedClusterAddonProfile; +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.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 Kubernetes Cluster. + * + * 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; + private ApiServerAccessProfile apiServerAccessProfile; + + /** + * 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; + } + + /** + * 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()); + 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()); + + 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); + + ApiServerAccessProfile apiServerAccessProfile = null; + if (cluster.innerModel().apiServerAccessProfile() != null) { + apiServerAccessProfile = newSubresource(ApiServerAccessProfile.class); + apiServerAccessProfile.copyFrom(cluster.innerModel().apiServerAccessProfile()); + } + setApiServerAccessProfile(apiServerAccessProfile); + } + + @Override + public boolean refresh() { + AzureResourceManager client = createClient(); + 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 = createClient(); + + 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.getMinimumNodeSize()) + + .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 (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()); + } + + 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()); + state.save(); + + KubernetesCluster.Update update; + if (getApiServerAccessProfile() != null) { + cluster.innerModel() + .withApiServerAccessProfile(getApiServerAccessProfile().toManagedClusterApiServerAccessProfile()); + } + + update = cluster.update(); + + if (getNetworkProfile() != null) { + NetworkProfile networkProfile = getNetworkProfile(); + setNetworkProfile(null); + 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 = createClient(); + + KubernetesCluster cluster = client.kubernetesClusters() + .getByResourceGroup(getResourceGroup().getName(), getName()); + + 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()) { + 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.getMinimumNodeSize()) + + .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 = createClient(); + + 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..eab6072d --- /dev/null +++ b/src/main/java/gyro/azure/containerservice/NetworkProfile.java @@ -0,0 +1,268 @@ +/* + * 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; +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. + */ + @Required + @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; + } +} diff --git a/src/main/java/gyro/azure/cosmosdb/CosmosDBAccountFinder.java b/src/main/java/gyro/azure/cosmosdb/CosmosDBAccountFinder.java index 5cc570b1..09d78a90 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 com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.cosmos.models.CosmosDBAccount; 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; /** * Query cosmos db. @@ -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..b99a25dd 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 = createClient(); 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 = 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) { - Azure client = createClient(); + AzureResourceManager client = createClient(); 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 = 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 5e108f76..d39ffb1b 100644 --- a/src/main/java/gyro/azure/dns/ARecordSetFinder.java +++ b/src/main/java/gyro/azure/dns/ARecordSetFinder.java @@ -16,9 +16,9 @@ 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.core.GyroException; @@ -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..8605b83f 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 = createClient(); - 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 = createClient(); - 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 = createClient(); 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 = 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 be5a159d..bb8a498e 100644 --- a/src/main/java/gyro/azure/dns/AaaaRecordSetFinder.java +++ b/src/main/java/gyro/azure/dns/AaaaRecordSetFinder.java @@ -16,9 +16,9 @@ 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.core.GyroException; @@ -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..3cd4449d 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 = createClient(); 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 = createClient(); - 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 = createClient(); 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 = createClient(); 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..407b5b53 100644 --- a/src/main/java/gyro/azure/dns/CaaRecordSetFinder.java +++ b/src/main/java/gyro/azure/dns/CaaRecordSetFinder.java @@ -16,9 +16,9 @@ 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.core.GyroException; @@ -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..75102bb3 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 = createClient(); 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 = createClient(); - 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 = createClient(); 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 = 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 251ea389..2178e503 100644 --- a/src/main/java/gyro/azure/dns/CnameRecordSetFinder.java +++ b/src/main/java/gyro/azure/dns/CnameRecordSetFinder.java @@ -16,9 +16,9 @@ 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.core.GyroException; @@ -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 AzureFinder { 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..6b823d26 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 = createClient(); - 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 = createClient(); - 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 = createClient(); 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 = 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 3f18cf8c..82dd0abb 100644 --- a/src/main/java/gyro/azure/dns/DnsZoneFinder.java +++ b/src/main/java/gyro/azure/dns/DnsZoneFinder.java @@ -16,8 +16,8 @@ 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.core.GyroException; @@ -26,6 +26,7 @@ import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; /** * Query dns zone. @@ -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..b8a8aeab 100644 --- a/src/main/java/gyro/azure/dns/DnsZoneResource.java +++ b/src/main/java/gyro/azure/dns/DnsZoneResource.java @@ -16,9 +16,12 @@ package gyro.azure.dns; +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.network.NetworkResource; import gyro.azure.resources.ResourceGroupResource; import gyro.core.GyroUI; import gyro.core.resource.Id; @@ -26,14 +29,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.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; @@ -48,7 +49,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,13 +59,13 @@ 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; + private List nsRecords; + private List nameServers; + /** * The ID of the Dns Zone. */ @@ -79,21 +79,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. */ @@ -107,79 +92,82 @@ public void setName(String name) { } /** - * A list of virtual network id's that register hostnames in a private Dns Zone. Can be used when the access is private. + * The Resource Group where the Dns Zone is found. */ - @Updatable - public Set getRegistrationNetwork() { - if (registrationNetwork == null) { - registrationNetwork = new HashSet<>(); - } - - return registrationNetwork; + @Required + public ResourceGroupResource getResourceGroup() { + return resourceGroup; } - public void setRegistrationNetwork(Set registrationNetwork) { - this.registrationNetwork = registrationNetwork; + public void setResourceGroup(ResourceGroupResource resourceGroup) { + this.resourceGroup = resourceGroup; } /** - * A list of virtual network id's that resolve records in a private Dns Zone. Can be used when the access is private. + * The tags associated with the Dns Zone. */ @Updatable - public Set getResolutionNetwork() { - if (resolutionNetwork == null) { - resolutionNetwork = new HashSet<>(); + public Map getTags() { + if (tags == null) { + tags = new HashMap<>(); } - return resolutionNetwork; + return tags; } - public void setResolutionNetwork(Set resolutionNetwork) { - this.resolutionNetwork = resolutionNetwork; + public void setTags(Map tags) { + this.tags = tags; } /** - * The Resource Group where the Dns Zone is found. + * List of ns record names present in the Dns Zone. */ - @Required - public ResourceGroupResource getResourceGroup() { - return resourceGroup; + @Output + public List getNsRecords() { + if (nsRecords == null) { + nsRecords = new ArrayList<>(); + } + + return nsRecords; } - public void setResourceGroup(ResourceGroupResource resourceGroup) { - this.resourceGroup = resourceGroup; + public void setNsRecords(List nsRecords) { + this.nsRecords = nsRecords; } /** - * The tags associated with the Dns Zone. + * A list of name servers present in the Dns Zone. */ - @Updatable - public Map getTags() { - if (tags == null) { - tags = new HashMap<>(); + @Output + public List getNameServers() { + if (nameServers == null) { + nameServers = new ArrayList<>(); } - return tags; + return nameServers; } - public void setTags(Map tags) { - this.tags = tags; + public void setNameServers(List nameServers) { + this.nameServers = nameServers; } @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()); + + setNsRecords(dnsZone.nsRecordSets().list().stream() + .map(HasName::name) + .collect(Collectors.toList())); + + setNameServers(dnsZone.nameServers()); } @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createClient(); DnsZone dnsZone = client.dnsZones().getById(getId()); @@ -194,33 +182,26 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createClient(); 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()); DnsZone dnsZone = withCreate.create(); - copyFrom(dnsZone); + setId(dnsZone.id()); + + copyFrom(client.dnsZones().getById(getId())); } @Override public void update(GyroUI ui, State state, Resource current, Set changedProperties) { - Azure client = createClient(); + AzureResourceManager client = createClient(); DnsZone.Update update = client.dnsZones().getById(getId()).update(); @@ -233,7 +214,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 = createClient(); 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..7de2405a 100644 --- a/src/main/java/gyro/azure/dns/MxRecordSetFinder.java +++ b/src/main/java/gyro/azure/dns/MxRecordSetFinder.java @@ -16,9 +16,9 @@ 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.core.GyroException; @@ -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 AzureFinder { 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..807ab752 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 = createClient(); - 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 = createClient(); - 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 = createClient(); 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 = 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 fc86fd12..34e69e47 100644 --- a/src/main/java/gyro/azure/dns/PtrRecordSetFinder.java +++ b/src/main/java/gyro/azure/dns/PtrRecordSetFinder.java @@ -16,9 +16,9 @@ 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.core.GyroException; @@ -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..0b9a4978 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 = createClient(); 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 = createClient(); - 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 = createClient(); 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 = createClient(); 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..3d30cc17 100644 --- a/src/main/java/gyro/azure/dns/SrvRecordSetFinder.java +++ b/src/main/java/gyro/azure/dns/SrvRecordSetFinder.java @@ -16,9 +16,9 @@ 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.core.GyroException; @@ -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..aaef32a4 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 = createClient(); 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 = createClient(); - 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 = 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) { - Azure client = createClient(); + 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 241fabd1..cde37c52 100644 --- a/src/main/java/gyro/azure/dns/TxtRecordSetFinder.java +++ b/src/main/java/gyro/azure/dns/TxtRecordSetFinder.java @@ -16,9 +16,9 @@ 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.core.GyroException; @@ -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..54b9447e 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 = createClient(); 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 = createClient(); - 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 = createClient(); 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 = 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 cc4aaa09..b3e8f259 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 com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.msi.models.Identity; 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; /** * Query identity. @@ -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..0f387215 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 = createClient(); 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 = 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 { - Azure client = createClient(); + 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 { - Azure client = createClient(); + AzureResourceManager client = createClient(); client.identities().deleteById(getId()); } 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/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/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..f885c0f5 100644 --- a/src/main/java/gyro/azure/keyvault/KeyVaultCertificateFinder.java +++ b/src/main/java/gyro/azure/keyvault/KeyVaultCertificateFinder.java @@ -20,9 +20,12 @@ 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 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.AzureFinder; 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 AzureFinder { 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..6f8008d0 100644 --- a/src/main/java/gyro/azure/keyvault/KeyVaultCertificatePolicy.java +++ b/src/main/java/gyro/azure/keyvault/KeyVaultCertificatePolicy.java @@ -17,151 +17,317 @@ 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. + */ + @ValidStrings({"RSA", "RSA-HSM", "EC", "EC-HSM"}) + public String getKeyType() { + return keyType; + } + + 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; + } + + 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; + } + + /** + * Enable or Disable transparency of the certificate. + */ + 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. */ @Required - public KeyVaultCertificateSecretProperties getSecretProperties() { - return secretProperties; + @Range(min = 1, max = 12) + public Integer getValidityInMonths() { + return validityInMonths; + } + + public void setValidityInMonths(Integer validityInMonths) { + this.validityInMonths = validityInMonths; } - public void setSecretProperties(KeyVaultCertificateSecretProperties secretProperties) { - this.secretProperties = secretProperties; + /** + * 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 setCreatedOn(Date createdOn) { + this.createdOn = createdOn; + } + + /** + * 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; } /** - * X509 properties for the certificate policy. + * 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 setSubjectAlternativeName(KeyVaultCertificateSubjectAlternativeName subjectAlternativeName) { + this.subjectAlternativeName = subjectAlternativeName; + } + + /** + * 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<>(); + } + + return keyUsage; + } + + public void setKeyUsage(List keyUsage) { + this.keyUsage = keyUsage; + } + + /** + * A list of enhanced key usage flags. + */ + public List getEnhancedKeyUsage() { + if (enhancedKeyUsage == null) { + enhancedKeyUsage = new ArrayList<>(); + } + + return enhancedKeyUsage; } - public void setX509Properties(KeyVaultCertificateX509Properties x509Properties) { - this.x509Properties = x509Properties; + public void setEnhancedKeyUsage(List enhancedKeyUsage) { + this.enhancedKeyUsage = enhancedKeyUsage; } /** - * Additional attributes for the certificate policy. + * 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 +336,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 417f6a56..ecf8dacd 100644 --- a/src/main/java/gyro/azure/keyvault/KeyVaultCertificateResource.java +++ b/src/main/java/gyro/azure/keyvault/KeyVaultCertificateResource.java @@ -16,23 +16,25 @@ 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; @@ -93,18 +95,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 +169,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 +181,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 +197,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 +227,50 @@ public void copyFrom(CertificateBundle certificateBundle) { @Override public boolean refresh() { - Vault vault = getVault().getKeyVault(); - 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().getKeyVault(); - 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,22 @@ public void update( @Override public void delete(GyroUI ui, State state) throws Exception { - Vault vault = getVault().getKeyVault(); - 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 + // TODO verify certificate exception, also affect finders and command + } + } + + 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/KeyVaultFinder.java b/src/main/java/gyro/azure/keyvault/KeyVaultFinder.java index 3c5d5640..28b30190 100644 --- a/src/main/java/gyro/azure/keyvault/KeyVaultFinder.java +++ b/src/main/java/gyro/azure/keyvault/KeyVaultFinder.java @@ -21,10 +21,9 @@ 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 com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.keyvault.models.Vault; +import com.azure.resourcemanager.resources.fluentcore.arm.models.HasName; import gyro.azure.AzureFinder; import gyro.core.Type; @@ -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..7e032694 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; @@ -30,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() { @@ -42,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() { @@ -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/KeyVaultKeyFinder.java b/src/main/java/gyro/azure/keyvault/KeyVaultKeyFinder.java index f6c831ee..6b5d510a 100644 --- a/src/main/java/gyro/azure/keyvault/KeyVaultKeyFinder.java +++ b/src/main/java/gyro/azure/keyvault/KeyVaultKeyFinder.java @@ -4,9 +4,9 @@ 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 com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.keyvault.models.Key; +import com.azure.resourcemanager.keyvault.models.Vault; 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 AzureFinder { +public class KeyVaultKeyFinder extends AzureFinder { 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/KeyVaultKeyResource.java b/src/main/java/gyro/azure/keyvault/KeyVaultKeyResource.java index 11096a02..d4967809 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; @@ -93,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; } @@ -132,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<>(); @@ -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..39f58f7d 100644 --- a/src/main/java/gyro/azure/keyvault/KeyVaultResource.java +++ b/src/main/java/gyro/azure/keyvault/KeyVaultResource.java @@ -22,10 +22,9 @@ import java.util.Set; import java.util.stream.Collectors; -import com.microsoft.azure.CloudException; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.keyvault.Vault; -import com.microsoft.azure.management.resources.fluentcore.arm.Region; +import com.azure.core.management.Region; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.keyvault.models.Vault; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.azure.resources.ResourceGroupResource; @@ -190,6 +189,7 @@ public class KeyVaultResource extends AzureResource implements Copyable { * The name of the key vault. */ @Required + @Id public String getName() { return name; } @@ -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() { @@ -339,7 +339,6 @@ public void setId(String id) { /** * The URI of the key vault. */ - @Id @Output public String getUrl() { return url; @@ -381,15 +380,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 = createClient(); - Vault vault = client.vaults().getById(getId()); + Vault vault = client.vaults().getByResourceGroup(getResourceGroup().getName(), getName()); if (vault == null) { return false; @@ -402,7 +401,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) throws Exception { - Azure client = createClient(); + AzureResourceManager client = createClient(); Vault.DefinitionStages.WithCreate withCreate = client.vaults().define(getName()) .withRegion(Region.fromName(getRegion())) @@ -438,13 +437,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 = createClient(); Vault vault = client.vaults().getById(getId()); @@ -507,24 +506,18 @@ public void update( @Override public void delete(GyroUI ui, State state) throws Exception { - Azure client = createClient(); + AzureResourceManager client = createClient(); 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() { - Azure client = createClient(); + AzureResourceManager client = createClient(); - return client.vaults().getById(getId()); + return client.vaults().getByResourceGroup(getResourceGroup().getName(), getName()); } } diff --git a/src/main/java/gyro/azure/keyvault/KeyVaultSecretAttribute.java b/src/main/java/gyro/azure/keyvault/KeyVaultSecretAttribute.java index ad14360b..0f4efd53 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; @@ -29,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() { @@ -41,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() { @@ -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/KeyVaultSecretFinder.java b/src/main/java/gyro/azure/keyvault/KeyVaultSecretFinder.java index 8a951d23..d30a964c 100644 --- a/src/main/java/gyro/azure/keyvault/KeyVaultSecretFinder.java +++ b/src/main/java/gyro/azure/keyvault/KeyVaultSecretFinder.java @@ -20,10 +20,9 @@ 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 com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.keyvault.models.Secret; +import com.azure.resourcemanager.keyvault.models.Vault; import gyro.azure.AzureFinder; 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 AzureFinder { 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/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()); } } 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 f193776b..0562fc17 100644 --- a/src/main/java/gyro/azure/network/AbstractApplicationGatewayCommand.java +++ b/src/main/java/gyro/azure/network/AbstractApplicationGatewayCommand.java @@ -2,15 +2,16 @@ import java.util.concurrent.Callable; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.network.ApplicationGateway; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.network.models.ApplicationGateway; import gyro.azure.AbstractAzureCommand; import gyro.core.GyroException; import gyro.core.command.GyroCommand; 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(); @@ -18,7 +19,7 @@ ApplicationGateway getApplicationGateway(String applicationGatewayResourceName) Resource resource = scope.findResource("azure::application-gateway::" + applicationGatewayResourceName); if (resource instanceof ApplicationGatewayResource) { - Azure client = getClient(); + AzureResourceManager client = getResourceManagerClient(); ApplicationGateway applicationGateway = client.applicationGateways() .getById(((ApplicationGatewayResource) resource).getId()); 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..397b5e37 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; diff --git a/src/main/java/gyro/azure/network/ApplicationGatewayFinder.java b/src/main/java/gyro/azure/network/ApplicationGatewayFinder.java index 1fea161c..13b1d873 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.AzureFinder; +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 AzureFinder { + 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..76a637c0 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 = createClient(); 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 = createClient(); 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 = createClient(); 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 = createClient(); 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 = createClient(); 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..729f4702 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.AzureFinder; +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 AzureFinder { + 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..537636c7 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 = createClient(); 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 = 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) { - Azure client = createClient(); + AzureResourceManager client = createClient(); client.applicationSecurityGroups().getById(getId()).update().withTags(getTags()).apply(); } @Override public void delete(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createClient(); 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/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/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..adb4c562 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; 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..d9c9246a 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.AzureFinder; +import gyro.core.Type; /** * Query load balancer. @@ -37,6 +38,7 @@ */ @Type("load-balancer") public class LoadBalancerFinder extends AzureFinder { + 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..b2004d77 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 = createClient(); 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 = createClient(); 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 = createClient(); 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 = createClient(); 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 916fb1ca..7cb963cc 100644 --- a/src/main/java/gyro/azure/network/NetworkFinder.java +++ b/src/main/java/gyro/azure/network/NetworkFinder.java @@ -16,17 +16,19 @@ package gyro.azure.network; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.network.Network; -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.Network; +import gyro.azure.AzureFinder; +import gyro.core.Type; @Type("network") public class NetworkFinder extends AzureFinder { + private String id; /** @@ -41,12 +43,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/NetworkInterfaceFinder.java b/src/main/java/gyro/azure/network/NetworkInterfaceFinder.java index 011f6e3b..0ef56833 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.AzureFinder; +import gyro.core.Type; /** * Query network interface. @@ -37,6 +38,7 @@ */ @Type("network-interface") public class NetworkInterfaceFinder extends AzureFinder { + 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..cad29c4c 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 = createClient(); NetworkInterface networkInterface = getNetworkInterface(client); @@ -236,7 +238,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createClient(); 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 = createClient(); 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 = createClient(); 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 a137b20d..e72508ab 100644 --- a/src/main/java/gyro/azure/network/NetworkResource.java +++ b/src/main/java/gyro/azure/network/NetworkResource.java @@ -16,30 +16,30 @@ 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 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; +import com.azure.resourcemanager.network.models.Subnet; 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.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Predicate; -import java.util.stream.Collectors; - /** * Creates a virtual network. * @@ -73,6 +73,7 @@ */ @Type("network") public class NetworkResource extends AzureResource implements Copyable { + private String name; private ResourceGroupResource resourceGroup; private Set addressSpaces; @@ -244,7 +245,7 @@ public void copyFrom(Network network) { @Override public boolean refresh() { - Azure client = createClient(); + AzureResourceManager client = createClient(); 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 = createClient(); 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 = createClient(); 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 = createClient(); client.networks().deleteById(getId()); } - Network getNetwork(Azure client) { + Network getNetwork(AzureResourceManager client) { return client.networks().getById(getId()); } } diff --git a/src/main/java/gyro/azure/network/NetworkSecurityGroupFinder.java b/src/main/java/gyro/azure/network/NetworkSecurityGroupFinder.java index abc0c19e..0f2b70d0 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.AzureFinder; +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 AzureFinder { + 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..06fdd0a5 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 = createClient(); 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 = createClient(); 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 = createClient(); 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 = 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 946c5b2a..c2162df9 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 = createClient(); 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 = createClient(); 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 = createClient(); 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..7dc70608 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 = createClient(); 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 = createClient(); 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 = createClient(); 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 40298e15..61e4c2e7 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 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.AzureFinder; +import gyro.core.Type; /** * Query public ip address. @@ -36,7 +37,8 @@ * public-ip-address: $(external-query azure::public-ip-address {}) */ @Type("public-ip-address") -public class PublicIpAddressFinder extends AzureFinder { +public class PublicIpAddressFinder extends AzureFinder { + private String id; /** @@ -51,13 +53,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..fe21d5e3 100644 --- a/src/main/java/gyro/azure/network/PublicIpAddressResource.java +++ b/src/main/java/gyro/azure/network/PublicIpAddressResource.java @@ -16,36 +16,35 @@ 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 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; +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; 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. * @@ -65,7 +64,8 @@ * 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; @@ -83,8 +83,6 @@ public class PublicIpAddressResource extends AzureResource implements Copyable

changedFieldNames) { - Azure client = createClient(); + AzureResourceManager client = createClient(); - 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 +418,19 @@ 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 = createClient(); + client.publicIpAddresses().deleteById(getId()); + } + + public enum SKU_TYPE { + BASIC, + STANDARD } } diff --git a/src/main/java/gyro/azure/network/RedirectConfiguration.java b/src/main/java/gyro/azure/network/RedirectConfiguration.java index 30443e52..ed61287d 100644 --- a/src/main/java/gyro/azure/network/RedirectConfiguration.java +++ b/src/main/java/gyro/azure/network/RedirectConfiguration.java @@ -16,12 +16,12 @@ package gyro.azure.network; -import com.microsoft.azure.management.network.ApplicationGateway.Update; -import com.microsoft.azure.management.network.ApplicationGatewayRedirectConfiguration; -import com.microsoft.azure.management.network.ApplicationGatewayRedirectConfiguration.UpdateDefinitionStages.WithTarget; -import com.microsoft.azure.management.network.ApplicationGatewayRedirectType; -import com.microsoft.azure.management.network.ApplicationGateway.DefinitionStages.WithCreate; -import com.microsoft.azure.management.network.ApplicationGatewayRedirectConfiguration.DefinitionStages; +import com.azure.resourcemanager.network.models.ApplicationGateway.DefinitionStages.WithCreate; +import com.azure.resourcemanager.network.models.ApplicationGateway.Update; +import com.azure.resourcemanager.network.models.ApplicationGatewayRedirectConfiguration; +import com.azure.resourcemanager.network.models.ApplicationGatewayRedirectConfiguration.DefinitionStages; +import com.azure.resourcemanager.network.models.ApplicationGatewayRedirectConfiguration.UpdateDefinitionStages.WithTarget; +import com.azure.resourcemanager.network.models.ApplicationGatewayRedirectType; import com.psddev.dari.util.ObjectUtils; import gyro.azure.Copyable; import gyro.core.resource.Diffable; @@ -46,6 +46,7 @@ * end */ public class RedirectConfiguration extends Diffable 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..b5f65c25 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; 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..f9cbc5a2 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.AzureFinder; +import gyro.core.Type; /** * Query route table. @@ -37,6 +38,7 @@ */ @Type("route-table") public class RouteTableFinder extends AzureFinder { + 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..5c657205 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 = createClient(); 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 = createClient(); 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 = createClient(); 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 = 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 9676d5d8..6dccd472 100644 --- a/src/main/java/gyro/azure/network/SubnetResource.java +++ b/src/main/java/gyro/azure/network/SubnetResource.java @@ -16,32 +16,31 @@ 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; +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.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.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. * @@ -63,7 +62,7 @@ public class SubnetResource extends AzureResource implements Copyable { private RouteTableResource routeTable; private Map> serviceEndpoints; private String id; - + /** * The address prefix in CIDR notation. */ @@ -145,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())); } @@ -157,7 +160,7 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createClient(); NetworkResource parent = (NetworkResource) parent(); @@ -182,12 +185,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 = createClient(); NetworkResource parent = (NetworkResource) parent(); @@ -212,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) { @@ -233,7 +237,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 = createClient(); NetworkResource parent = (NetworkResource) parent(); @@ -251,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()); } 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..8ddfd5e2 --- /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.AzureFinder; +import gyro.core.Type; + +/** + * Query registry. + * + * Example + * ------- + * + * .. code-block:: gyro + * + * registry: $(external-query azure::registry {}) + */ +@Type("registry") +public class RegistryFinder extends AzureFinder { + + 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..d8bbe349 --- /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 = createClient(); + + 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 = createClient(); + + 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 = createClient(); + + 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 = createClient(); + + 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; diff --git a/src/main/java/gyro/azure/resources/ResourceGroupFinder.java b/src/main/java/gyro/azure/resources/ResourceGroupFinder.java index 09a310c7..5deb8fc8 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 com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.resources.models.ResourceGroup; 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; /** * Query resource group. @@ -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..a772d5a1 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 = createClient(); 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 = 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) { - Azure client = createClient(); + 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) { - Azure client = createClient(); + 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 528a19a7..43738515 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.AzureFinder; +import gyro.core.Type; + /** * Query sql database. * @@ -40,6 +40,7 @@ */ @Type("sql-database") public class SqlDatabaseFinder extends AzureFinder { + 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..35ab9bd8 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 = createClient(); SqlDatabase database = getSqlDatabase(client); @@ -339,18 +345,21 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createClient(); - 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 = createClient(); 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 = createClient(); 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..361fd996 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.AzureFinder; +import gyro.core.Type; + /** * Query sql elastic pool. * @@ -40,6 +40,7 @@ */ @Type("sql-elastic-pool") public class SqlElasticPoolFinder extends AzureFinder { + 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..f0095378 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 = createClient(); 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 = createClient(); - 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 = createClient(); 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 = createClient(); 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..3ee123f8 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.AzureFinder; +import gyro.core.Type; + /** * Query sql failover group. * @@ -40,6 +40,7 @@ */ @Type("sql-failover-group") public class SqlFailoverGroupFinder extends AzureFinder { + 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..f5bd9528 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 = createClient(); SqlFailoverGroup failoverGroup = getSqlFailoverGroup(client); @@ -227,16 +225,20 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) { - Azure client = createClient(); + AzureResourceManager client = createClient(); - 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 = createClient(); 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 = createClient(); 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..6f36493b 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.AzureFinder; +import gyro.core.Type; + /** * Query sql firewall rule. * @@ -40,6 +40,7 @@ */ @Type("sql-firewall-rule") public class SqlFirewallRuleFinder extends AzureFinder { + 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..a758102d 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 = createClient(); 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 = createClient(); - 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 = createClient(); 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 = createClient(); 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..fa8fe383 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.AzureFinder; +import gyro.core.Type; /** * Query sql server. @@ -37,6 +38,7 @@ */ @Type("sql-server") public class SqlServerFinder extends AzureFinder { + 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..7527cc5d 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 = createClient(); 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 = createClient(); 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 = createClient(); 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 = 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 01b9cbbc..56435f74 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.AzureFinder; +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 AzureFinder { + 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..09558268 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 = createClient(); 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 = createClient(); + + 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 = createClient(); 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 = createClient(); 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()); diff --git a/src/main/java/gyro/azure/storage/CloudBlobContainerResource.java b/src/main/java/gyro/azure/storage/CloudBlobContainerResource.java index 7b472a37..4f52cf14 100644 --- a/src/main/java/gyro/azure/storage/CloudBlobContainerResource.java +++ b/src/main/java/gyro/azure/storage/CloudBlobContainerResource.java @@ -16,30 +16,26 @@ package gyro.azure.storage; +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.GyroException; 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 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.resource.Updatable; 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.Set; - /** * Creates a blob container * @@ -50,17 +46,18 @@ * * 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; 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. */ @Required - @ValidStrings({"BLOB", "CONTAINER", "OFF"}) + @ValidStrings({ "blob", "container" }) @Updatable public String getPublicAccess() { return publicAccess; @@ -101,6 +98,19 @@ public void setStorageAccount(StorageAccountResource storageAccount) { this.storageAccount = storageAccount; } + @Updatable + 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 +124,68 @@ 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(BlobContainerClient container) { + setPublicAccess(container.getAccessPolicy().getBlobAccessType().toString()); + setName(container.getBlobContainerName()); + setMetadata(container.getProperties().getMetadata()); + setStorageAccount(findById(StorageAccountResource.class, container.getAccountName())); } @Override public boolean refresh() { - try { - CloudBlobContainer container = cloudBlobContainer(); - if (!container.exists()) { - return false; - } + BlobContainerClient blobContainer = blobContainer(); - copyFrom(container); - - return true; - } catch (StorageException ex) { + if (!blobContainer.exists()) { 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()); + BlobContainerClient blobContainer = blobContainer(); + + blobContainer.create(); + + blobContainer = blobContainer(); + + blobContainer.setAccessPolicy(PublicAccessType.fromString(getPublicAccess()), null); + + if (!getMetadata().isEmpty()) { + blobContainer.setMetadata(getMetadata()); } + + 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()); + BlobContainerClient blobContainer = blobContainer(); + + if (changedFieldNames.contains("metadata")) { + blobContainer.setMetadata(getMetadata()); + } + + if (changedFieldNames.contains("public-access")) { + blobContainer.setAccessPolicy(PublicAccessType.fromString(getPublicAccess()), null); } } @Override public void delete(GyroUI ui, State state) { - try { - CloudBlobContainer container = cloudBlobContainer(); - container.delete(); - } catch (StorageException ex) { - throw new GyroException(ex.getMessage()); - } + BlobContainerClient blobContainer = blobContainer(); + + blobContainer.delete(); } - 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()); - } + protected BlobContainerClient blobContainer() { + BlobServiceClient client = new BlobServiceClientBuilder() + .connectionString(getStorageAccount().getConnection()) + .buildClient(); + + 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..6f3432e4 100644 --- a/src/main/java/gyro/azure/storage/PolicyFilter.java +++ b/src/main/java/gyro/azure/storage/PolicyFilter.java @@ -16,22 +16,25 @@ 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; +import gyro.core.validation.ValidStrings; + public class PolicyFilter extends Diffable implements Copyable { + private Set blobTypes; private Set 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 830eb084..2a48481d 100644 --- a/src/main/java/gyro/azure/storage/PolicyRule.java +++ b/src/main/java/gyro/azure/storage/PolicyRule.java @@ -16,13 +16,16 @@ 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; +import gyro.core.validation.ValidStrings; public class PolicyRule extends Diffable implements Copyable { + private String name; private String type; private Boolean enabled; @@ -41,11 +44,12 @@ public void setName(String name) { } /** - * Type of rule. Currently only supported value is ``Lifecycle``. Defaults to ``Lifecycle``. + * Type of rule. */ + @ValidStrings("Lifecycle") public String getType() { if (type == null) { - type = "Lifecycle"; + type = RuleType.LIFECYCLE.toString(); } return type; @@ -74,7 +78,7 @@ public void setEnabled(Boolean enabled) { /** * The rule details. * - * @sunresource gyro.azure.storage.PolicyDefinition + * @subresource gyro.azure.storage.PolicyDefinition */ @Required @Updatable @@ -94,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()); @@ -103,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/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 8be78205..f406e694 100644 --- a/src/main/java/gyro/azure/storage/StorageAccountFinder.java +++ b/src/main/java/gyro/azure/storage/StorageAccountFinder.java @@ -16,18 +16,23 @@ package gyro.azure.storage; -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.storage.StorageAccount; -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.storage.models.StorageAccount; +import gyro.azure.AzureFinder; +import gyro.core.GyroException; +import gyro.core.Type; @Type("storage-account") public class StorageAccountFinder extends AzureFinder { + private String id; + private String resourceGroup; + private String name; /** * The ID of the Storage Account. @@ -40,14 +45,45 @@ 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(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) { - StorageAccount storageAccount = client.storageAccounts().getById(filters.get("id")); + protected List findAzure(AzureResourceManager client, Map filters) { + 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 9e9d098e..6eebb73b 100644 --- a/src/main/java/gyro/azure/storage/StorageAccountResource.java +++ b/src/main/java/gyro/azure/storage/StorageAccountResource.java @@ -16,41 +16,30 @@ 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 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; +import com.azure.resourcemanager.storage.models.StorageAccount; 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.resources.fluentcore.arm.Region; -import com.microsoft.azure.management.storage.StorageAccount; -import com.microsoft.azure.management.storage.StorageAccountKey; +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.List; -import java.util.Map; -import java.util.Set; - /** * Creates a storage account * @@ -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,14 @@ 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 = createClient(); - StorageAccount storageAccount = client.storageAccounts().getById(getId()); + StorageAccount storageAccount = client.storageAccounts() + .getByResourceGroup(getResourceGroup().getName(), getName()); if (storageAccount == null) { return false; @@ -300,8 +233,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 = createClient(); StorageAccount.DefinitionStages.WithCreate withCreate = client.storageAccounts() .define(getName()) @@ -317,12 +250,13 @@ 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 = createClient(); StorageAccount storageAccount = client.storageAccounts().getById(getId()); StorageAccount.Update update = storageAccount.update(); @@ -338,61 +272,27 @@ 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 = createClient(); 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() + ";" - + "AccountKey=" + keys().get("key1"); + return String.format("DefaultEndpointsProtocol=https;" + + "AccountName=%s;" + + "AccountKey=%s;" + + "EndpointSuffix=core.windows.net", getName(), keys().get("key1")); } public Map keys() { Map keys = new HashMap<>(); if (getId() != null) { - Azure client = createClient(); + AzureResourceManager client = createClient(); StorageAccount storageAccount = client.storageAccounts().getById(getId()); storageAccount.getKeys().forEach(e -> keys.put(e.keyName(), e.value())); @@ -400,4 +300,10 @@ public Map keys() { return keys; } + + protected StorageAccount getStorageAccount() { + 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 f0f11dbb..1040df37 100644 --- a/src/main/java/gyro/azure/storage/StorageLifeCycle.java +++ b/src/main/java/gyro/azure/storage/StorageLifeCycle.java @@ -16,14 +16,20 @@ 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.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; import gyro.core.GyroException; @@ -35,20 +41,15 @@ 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; private Set 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() { @@ -115,7 +116,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 +133,45 @@ public boolean refresh() { @Override public void create(GyroUI ui, State state) throws Exception { - Azure client = createClient(); + AzureResourceManager client = createClient(); 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(); + 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())) + .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(); } @@ -169,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 { @@ -179,7 +192,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 = createClient(); ManagementPolicySchema policySchema = new ManagementPolicySchema(); policySchema.withRules(getRule().stream().map(PolicyRule::toManagementPolicyRule).collect(Collectors.toList())); @@ -192,25 +205,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 = createClient(); 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(); } }