コード例 #1
0
        public static PSVirtualMachineInstanceView ToPSVirtualMachineInstanceView(
            this VirtualMachineInstanceView virtualMachineInstanceView,
            string resourceGroupName = null,
            string vmName            = null)
        {
            PSVirtualMachineInstanceView result = new PSVirtualMachineInstanceView
            {
                ResourceGroupName = resourceGroupName,
                Name                      = vmName,
                BootDiagnostics           = virtualMachineInstanceView.BootDiagnostics,
                Disks                     = virtualMachineInstanceView.Disks,
                Extensions                = virtualMachineInstanceView.Extensions,
                Statuses                  = virtualMachineInstanceView.Statuses,
                PlatformFaultDomain       = virtualMachineInstanceView.PlatformFaultDomain,
                PlatformUpdateDomain      = virtualMachineInstanceView.PlatformUpdateDomain,
                RemoteDesktopThumbprint   = virtualMachineInstanceView.RdpThumbPrint,
                VMAgent                   = virtualMachineInstanceView.VmAgent,
                MaintenanceRedeployStatus = virtualMachineInstanceView.MaintenanceRedeployStatus,
                ComputerName              = virtualMachineInstanceView.ComputerName,
                OsName                    = virtualMachineInstanceView.OsName,
                OsVersion                 = virtualMachineInstanceView.OsVersion,
                HyperVGeneration          = virtualMachineInstanceView.HyperVGeneration
            };

            return(result);
        }
コード例 #2
0
 internal VirtualMachineData(ResourceIdentifier id, string name, ResourceType type, SystemData systemData, IDictionary <string, string> tags, AzureLocation location, Models.Plan plan, IReadOnlyList <VirtualMachineExtensionData> resources, ManagedServiceIdentity identity, IList <string> zones, Models.ExtendedLocation extendedLocation, HardwareProfile hardwareProfile, StorageProfile storageProfile, AdditionalCapabilities additionalCapabilities, OSProfile osProfile, NetworkProfile networkProfile, SecurityProfile securityProfile, DiagnosticsProfile diagnosticsProfile, WritableSubResource availabilitySet, WritableSubResource virtualMachineScaleSet, WritableSubResource proximityPlacementGroup, VirtualMachinePriorityTypes?priority, VirtualMachineEvictionPolicyTypes?evictionPolicy, BillingProfile billingProfile, WritableSubResource host, WritableSubResource hostGroup, string provisioningState, VirtualMachineInstanceView instanceView, string licenseType, string vmId, string extensionsTimeBudget, int?platformFaultDomain, ScheduledEventsProfile scheduledEventsProfile, string userData, CapacityReservationProfile capacityReservation, ApplicationProfile applicationProfile) : base(id, name, type, systemData, tags, location)
 {
     Plan                    = plan;
     Resources               = resources;
     Identity                = identity;
     Zones                   = zones;
     ExtendedLocation        = extendedLocation;
     HardwareProfile         = hardwareProfile;
     StorageProfile          = storageProfile;
     AdditionalCapabilities  = additionalCapabilities;
     OSProfile               = osProfile;
     NetworkProfile          = networkProfile;
     SecurityProfile         = securityProfile;
     DiagnosticsProfile      = diagnosticsProfile;
     AvailabilitySet         = availabilitySet;
     VirtualMachineScaleSet  = virtualMachineScaleSet;
     ProximityPlacementGroup = proximityPlacementGroup;
     Priority                = priority;
     EvictionPolicy          = evictionPolicy;
     BillingProfile          = billingProfile;
     Host                    = host;
     HostGroup               = hostGroup;
     ProvisioningState       = provisioningState;
     InstanceView            = instanceView;
     LicenseType             = licenseType;
     VmId                    = vmId;
     ExtensionsTimeBudget    = extensionsTimeBudget;
     PlatformFaultDomain     = platformFaultDomain;
     ScheduledEventsProfile  = scheduledEventsProfile;
     UserData                = userData;
     CapacityReservation     = capacityReservation;
     ApplicationProfile      = applicationProfile;
 }
コード例 #3
0
        public void GetVMInstanceViewWithPatchStatus()
        {
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                EnsureClientsInitialized(context);
                VirtualMachineInstanceView vmInstanceView = m_CrpClient.VirtualMachines.InstanceView(RgName, VmName);

                Assert.NotNull(vmInstanceView);
                Assert.NotNull(vmInstanceView.PatchStatus);
                Assert.NotNull(vmInstanceView.PatchStatus.AvailablePatchSummary);
                Assert.Equal(0, vmInstanceView.PatchStatus.AvailablePatchSummary.CriticalAndSecurityPatchCount);
                Assert.Equal(1, vmInstanceView.PatchStatus.AvailablePatchSummary.OtherPatchCount);
                Assert.True(vmInstanceView.PatchStatus.AvailablePatchSummary.RebootPending);
                Assert.NotNull(vmInstanceView.PatchStatus.AvailablePatchSummary.StartTime);
                Assert.NotNull(vmInstanceView.PatchStatus.AvailablePatchSummary.LastModifiedTime);
                Assert.NotNull(vmInstanceView.PatchStatus.AvailablePatchSummary.AssessmentActivityId);
                Assert.NotNull(vmInstanceView.PatchStatus.LastPatchInstallationSummary);
                Assert.Equal("Succeeded", vmInstanceView.PatchStatus.LastPatchInstallationSummary.Status);
                Assert.Equal(0, vmInstanceView.PatchStatus.LastPatchInstallationSummary.ExcludedPatchCount);
                Assert.Equal(0, vmInstanceView.PatchStatus.LastPatchInstallationSummary.FailedPatchCount);
                Assert.Equal(0, vmInstanceView.PatchStatus.LastPatchInstallationSummary.NotSelectedPatchCount);
                Assert.Equal(2, vmInstanceView.PatchStatus.LastPatchInstallationSummary.InstalledPatchCount);
                Assert.Equal(0, vmInstanceView.PatchStatus.LastPatchInstallationSummary.PendingPatchCount);
                Assert.NotNull(vmInstanceView.PatchStatus.LastPatchInstallationSummary.InstallationActivityId);
                //Assert.False(vmInstanceView.PatchStatus.LastPatchInstallationSummary.MaintenanceWindowExceeded);
                Assert.NotNull(vmInstanceView.PatchStatus.LastPatchInstallationSummary.StartTime);
                Assert.NotNull(vmInstanceView.PatchStatus.LastPatchInstallationSummary.LastModifiedTime);

                //Assert.NotNull(vmInstanceView.PatchStatus.ConfigurationStatusSummary);
                //Assert.NotNull(vmInstanceView.PatchStatus.ConfigurationStatusSummary.LastModifiedTime);
                //Assert.Equal("Ready", vmInstanceView.PatchStatus.ConfigurationStatusSummary.PatchModeProvisioningState);
            }
        }
コード例 #4
0
 /// <summary>
 /// Creates an instance of PowerState from the virtual machine instance view status entry corresponding
 /// to the power state.
 /// </summary>
 /// <param name="virtualMachineInstanceView">the virtual machine instance view</param>
 /// <returns>the PowerState</returns>
 public static PowerState FromInstanceView(VirtualMachineInstanceView virtualMachineInstanceView)
 {
     if (virtualMachineInstanceView != null && virtualMachineInstanceView.Statuses != null)
     {
         return((from status in virtualMachineInstanceView.Statuses
                 where status.Code != null && status.Code.StartsWith("PowerState")
                 select Parse(status.Code)).FirstOrDefault());
     }
     return(null);
 }
コード例 #5
0
        private EncryptionStatus AreDataVolumesEncrypted(VirtualMachine vmParameters)
        {
            // return true if any (non-OS) data volume attached to the VM reports an encrypted state
            VirtualMachineInstanceView iv = this.ComputeClient.ComputeManagementClient.VirtualMachines.InstanceView(this.ResourceGroupName, this.VMName);

            foreach (DiskInstanceView div in iv.Disks)
            {
                if (!((div.Name.Equals("osDisk") || div.Name.Contains("_OsDisk_"))) &&
                    GetLastEncryptionStatus(div).Equals("EncryptionState/encrypted"))
                {
                    return(EncryptionStatus.Encrypted);
                }
            }

            // no encrypted status found in disk instance data, check vm model
            if (vmParameters == null || vmParameters.Resources == null)
            {
                return(EncryptionStatus.Unknown);
            }

            OSType osType = this.GetOSType(vmParameters);

            foreach (VirtualMachineExtension vmExtension in vmParameters.Resources)
            {
                switch (osType)
                {
                case OSType.Windows:
                case OSType.Linux:
                    if (IsAzureDiskEncryptionExtension(osType, vmExtension))
                    {
                        AzureDiskEncryptionExtensionContext adeExtension = new AzureDiskEncryptionExtensionContext(vmExtension.ToPSVirtualMachineExtension(this.ResourceGroupName, this.VMName));
                        if (DataVolumeInExtensionConfig(adeExtension))
                        {
                            if (adeExtension.EncryptionOperation.Equals(AzureDiskEncryptionExtensionConstants.enableEncryptionOperation, StringComparison.InvariantCultureIgnoreCase))
                            {
                                if (ExtensionProvisioningSucceeded(adeExtension))
                                {
                                    return(EncryptionStatus.Encrypted);
                                }
                            }
                        }
                    }
                    break;

                case OSType.Unknown:
                    return(EncryptionStatus.Unknown);

                default:
                    return(EncryptionStatus.Unknown);
                }
            }
            return(EncryptionStatus.NotEncrypted);
        }
コード例 #6
0
        private AzureDiskEncryptionStatusContext GetStatusFromInstanceView()
        {
            AzureDiskEncryptionStatusContext result = null;

            VirtualMachineInstanceView iv = this.ComputeClient.ComputeManagementClient.VirtualMachines.InstanceView(this.ResourceGroupName, this.VMName);

            if (iv != null)
            {
                result = new AzureDiskEncryptionStatusContext();
                result.OsVolumeEncrypted    = EncryptionStatus.Unknown;
                result.DataVolumesEncrypted = EncryptionStatus.Unknown;

                foreach (DiskInstanceView div in iv.Disks)
                {
                    if (result.OsVolumeEncrypted == EncryptionStatus.Unknown &&
                        (div.Name.Equals("osDisk") || div.Name.Contains("_OsDisk_")))
                    {
                        // check os volume status
                        string status = GetLastEncryptionStatus(div);
                        switch (status)
                        {
                        case "EncryptionState/encrypted":
                            result.OsVolumeEncrypted = EncryptionStatus.Encrypted;
                            break;

                        case "EncryptionState/notEncrypted":
                            result.OsVolumeEncrypted = EncryptionStatus.NotEncrypted;
                            break;

                        default:
                            break;
                        }
                        result.OsVolumeEncryptionSettings = (div.EncryptionSettings != null) ? div.EncryptionSettings[0] : null;
                    }
                    else if (result.DataVolumesEncrypted == EncryptionStatus.Unknown)
                    {
                        // check data volume status
                        string status = GetLastEncryptionStatus(div);
                        if (status.Equals("EncryptionState/encrypted"))
                        {
                            result.DataVolumesEncrypted = EncryptionStatus.Encrypted;
                        }
                        else if (status.Equals("EncryptionState/notEncrypted"))
                        {
                            result.DataVolumesEncrypted = EncryptionStatus.NotEncrypted;
                        }
                    }
                }
            }

            return(result);
        }
コード例 #7
0
        internal VirtualMachineExtensionInstanceView GetExtension(VirtualMachine vm, VirtualMachineInstanceView vmStatus, string type, string publisher)
        {
            var ext = this.GetExtension(vm, type, publisher);

            if (ext == null)
            {
                return(null);
            }

            if (vmStatus.Extensions == null)
            {
                return(null);
            }
            return(vmStatus.Extensions.FirstOrDefault(extSt => extSt.Name.Equals(ext.Name)));
        }
 ///GENMHASH:56E00E1F789510BB94AFCDC1FF61D00B:C0B660115AA9DC53D76DEDA856496556
 internal VirtualMachineScaleSetVMImpl(VirtualMachineScaleSetVMInner inner, VirtualMachineScaleSetImpl parent)
     : base(inner, parent)
 {
     if (inner.InstanceView != null)
     {
         virtualMachineInstanceView = new VirtualMachineInstanceView(
             Inner.InstanceView.PlatformFaultDomain, Inner.InstanceView.PlatformUpdateDomain, null,
             null, null, default(HyperVGenerationType), Inner.InstanceView.RdpThumbPrint,
             Inner.InstanceView.VmAgent, Inner.InstanceView.MaintenanceRedeployStatus, Inner.InstanceView.Disks,
             Inner.InstanceView.Extensions, Inner.InstanceView.BootDiagnostics, Inner.InstanceView.Statuses);
     }
     else
     {
         virtualMachineInstanceView = null;
     }
 }
コード例 #9
0
        public static PSVirtualMachineInstanceView ToPSVirtualMachineInstanceView(
            this VirtualMachineInstanceView virtualMachineInstanceView,
            string resourceGroupName = null,
            string vmName            = null)
        {
            PSVirtualMachineInstanceView result = new PSVirtualMachineInstanceView
            {
                ResourceGroupName = resourceGroupName,
                Name                    = vmName,
                Disks                   = virtualMachineInstanceView.Disks,
                Extensions              = virtualMachineInstanceView.Extensions,
                Statuses                = virtualMachineInstanceView.Statuses,
                PlatformFaultDomain     = virtualMachineInstanceView.PlatformFaultDomain,
                PlatformUpdateDomain    = virtualMachineInstanceView.PlatformUpdateDomain,
                RemoteDesktopThumbprint = virtualMachineInstanceView.RemoteDesktopThumbprint,
                VMAgent                 = virtualMachineInstanceView.VMAgent
            };

            return(result);
        }
コード例 #10
0
        public void GetVMInstanceViewWithPatchStatus()
        {
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                EnsureClientsInitialized(context);
                VirtualMachineInstanceView vmInstanceView = m_CrpClient.VirtualMachines.InstanceView(RgName, VmName);

                Assert.NotNull(vmInstanceView);
                Assert.NotNull(vmInstanceView.PatchStatus);

                /* These asserts could not be re-recorded as we do not have the knowledge to manually setup the required objects.
                 * They will be added back in by the API owning team.
                 *
                 * Assert.NotNull(vmInstanceView.PatchStatus.AvailablePatchSummary);
                 * Assert.Equal(0, vmInstanceView.PatchStatus.AvailablePatchSummary.CriticalAndSecurityPatchCount);
                 * Assert.Equal(1, vmInstanceView.PatchStatus.AvailablePatchSummary.OtherPatchCount);
                 * Assert.True(vmInstanceView.PatchStatus.AvailablePatchSummary.RebootPending);
                 * Assert.NotNull(vmInstanceView.PatchStatus.AvailablePatchSummary.StartTime);
                 * Assert.NotNull(vmInstanceView.PatchStatus.AvailablePatchSummary.LastModifiedTime);
                 * Assert.NotNull(vmInstanceView.PatchStatus.AvailablePatchSummary.AssessmentActivityId);
                 * Assert.NotNull(vmInstanceView.PatchStatus.LastPatchInstallationSummary);
                 * Assert.Equal("Succeeded", vmInstanceView.PatchStatus.LastPatchInstallationSummary.Status);
                 * Assert.Equal(0, vmInstanceView.PatchStatus.LastPatchInstallationSummary.ExcludedPatchCount);
                 * Assert.Equal(0, vmInstanceView.PatchStatus.LastPatchInstallationSummary.FailedPatchCount);
                 * Assert.Equal(0, vmInstanceView.PatchStatus.LastPatchInstallationSummary.NotSelectedPatchCount);
                 * Assert.Equal(2, vmInstanceView.PatchStatus.LastPatchInstallationSummary.InstalledPatchCount);
                 * Assert.Equal(0, vmInstanceView.PatchStatus.LastPatchInstallationSummary.PendingPatchCount);
                 * Assert.NotNull(vmInstanceView.PatchStatus.LastPatchInstallationSummary.InstallationActivityId);
                 * //Assert.False(vmInstanceView.PatchStatus.LastPatchInstallationSummary.MaintenanceWindowExceeded);//This was already commented out before.
                 * Assert.NotNull(vmInstanceView.PatchStatus.LastPatchInstallationSummary.StartTime);
                 * Assert.NotNull(vmInstanceView.PatchStatus.LastPatchInstallationSummary.LastModifiedTime);
                 *
                 * The below asserts were already commented out before.*/

                //Assert.NotNull(vmInstanceView.PatchStatus.ConfigurationStatusSummary);
                //Assert.NotNull(vmInstanceView.PatchStatus.ConfigurationStatusSummary.LastModifiedTime);
                //Assert.Equal("Ready", vmInstanceView.PatchStatus.ConfigurationStatusSummary.PatchModeProvisioningState);
            }
        }
コード例 #11
0
        internal Version GetExtensionVersion(VirtualMachine vm, VirtualMachineInstanceView vmStatus, string osType, string type, string publisher)
        {
            Version version = new Version();

            if (AEMExtensionConstants.AEMExtensionPublisher[osType].Equals(publisher, StringComparison.InvariantCultureIgnoreCase) &&
                AEMExtensionConstants.AEMExtensionType[osType].Equals(type, StringComparison.InvariantCultureIgnoreCase))
            {
                version = AEMExtensionConstants.AEMExtensionVersion[osType];
            }
            else if (AEMExtensionConstants.WADExtensionPublisher[osType].Equals(publisher, StringComparison.InvariantCultureIgnoreCase) &&
                     AEMExtensionConstants.WADExtensionType[osType].Equals(type, StringComparison.InvariantCultureIgnoreCase))
            {
                version = AEMExtensionConstants.WADExtensionVersion[osType];
            }

            if (vm.Resources != null && vmStatus.Extensions != null)
            {
                var extension = vm.Resources.FirstOrDefault(ext =>
                                                            ext.VirtualMachineExtensionType.Equals(type) &&
                                                            ext.Publisher.Equals(publisher));

                if (extension != null)
                {
                    var extensionStatus = vmStatus.Extensions.FirstOrDefault(ext => ext.Name.Equals(extension.Name));

                    if (extensionStatus != null)
                    {
                        string  strExtVersion = extensionStatus.TypeHandlerVersion;
                        Version extVersion;
                        if (Version.TryParse(strExtVersion, out extVersion) && extVersion > version)
                        {
                            version = extVersion;
                        }
                    }
                }
            }
            return(version);
        }
コード例 #12
0
        ///GENMHASH:F5949CB4AFA8DD0B8DED0F369B12A8F6:E8FB723EB69B1FF154465213A3298460
        public VirtualMachineInstanceView RefreshInstanceView()
        {
            VirtualMachineScaleSetVMInstanceViewInner instanceViewInner = Management.ResourceManager.Fluent.Core.Extensions.Synchronize(() => Parent.Manager.Inner.VirtualMachineScaleSetVMs.GetInstanceViewAsync(
                                                                                                                                            Parent.ResourceGroupName,
                                                                                                                                            Parent.Name,
                                                                                                                                            InstanceId()));

            if (instanceViewInner != null)
            {
                this.virtualMachineInstanceView = new VirtualMachineInstanceView()
                {
                    BootDiagnostics      = instanceViewInner.BootDiagnostics,
                    Disks                = instanceViewInner.Disks,
                    Extensions           = instanceViewInner.Extensions,
                    PlatformFaultDomain  = instanceViewInner.PlatformFaultDomain,
                    PlatformUpdateDomain = instanceViewInner.PlatformUpdateDomain,
                    RdpThumbPrint        = instanceViewInner.RdpThumbPrint,
                    Statuses             = instanceViewInner.Statuses,
                    VmAgent              = instanceViewInner.VmAgent
                };
            }
            return(this.virtualMachineInstanceView);
        }
        public async Task <Models.VirtualMachineInstanceView> RefreshInstanceViewAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            var instanceViewInner = await Parent.Manager.Inner.VirtualMachineScaleSetVMs.GetInstanceViewAsync(
                this.Parent.ResourceGroupName,
                this.Parent.Name,
                this.InstanceId());

            if (instanceViewInner != null)
            {
                this.virtualMachineInstanceView = new VirtualMachineInstanceView()
                {
                    BootDiagnostics      = instanceViewInner.BootDiagnostics,
                    Disks                = instanceViewInner.Disks,
                    Extensions           = instanceViewInner.Extensions,
                    PlatformFaultDomain  = instanceViewInner.PlatformFaultDomain,
                    PlatformUpdateDomain = instanceViewInner.PlatformUpdateDomain,
                    RdpThumbPrint        = instanceViewInner.RdpThumbPrint,
                    Statuses             = instanceViewInner.Statuses,
                    VmAgent              = instanceViewInner.VmAgent
                };
            }
            return(this.virtualMachineInstanceView);
        }
コード例 #14
0
        public void CanCreateVirtualMachinesAndAvailabilitySetInSameProximityPlacementGroup()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                var RGName         = TestUtilities.GenerateName("rgfluentchash-");
                var AvailName      = TestUtilities.GenerateName("availset1");
                var ProxyGroupName = TestUtilities.GenerateName("testproxgroup1");
                var ProxyGroupType = ProximityPlacementGroupType.Standard;
                var RegionPPG      = Region.USWestCentral;

                var computeManager  = TestHelper.CreateComputeManager();
                var resourceManager = TestHelper.CreateResourceManager();

                try
                {
                    var setCreated = computeManager.AvailabilitySets
                                     .Define(AvailName)
                                     .WithRegion(RegionPPG)
                                     .WithNewResourceGroup(RGName)
                                     .WithNewProximityPlacementGroup(ProxyGroupName, ProxyGroupType)
                                     .Create();

                    Assert.Equal(AvailName, setCreated.Name);
                    Assert.NotNull(setCreated.ProximityPlacementGroup);
                    Assert.Equal(ProxyGroupType, setCreated.ProximityPlacementGroup.ProximityPlacementGroupType);
                    Assert.NotNull(setCreated.ProximityPlacementGroup.AvailabilitySetIds);
                    Assert.True(setCreated.ProximityPlacementGroup.AvailabilitySetIds.Count > 0);
                    Assert.Equal(setCreated.Id, setCreated.ProximityPlacementGroup.AvailabilitySetIds[0], true);
                    Assert.Equal(setCreated.RegionName, setCreated.ProximityPlacementGroup.Location);

                    // Create
                    computeManager.VirtualMachines
                    .Define(VMName)
                    .WithRegion(RegionPPG)
                    .WithExistingResourceGroup(RGName)
                    .WithNewPrimaryNetwork("10.0.0.0/28")
                    .WithPrimaryPrivateIPAddressDynamic()
                    .WithoutPrimaryPublicIPAddress()
                    .WithProximityPlacementGroup(setCreated.ProximityPlacementGroup.Id)
                    .WithPopularWindowsImage(KnownWindowsVirtualMachineImage.WindowsServer2012Datacenter)
                    .WithAdminUsername("Foo12")
                    .WithAdminPassword("abc!@#F0orL")
                    .WithUnmanagedDisks()
                    .WithSize(VirtualMachineSizeTypes.StandardDS3V2)
                    .WithOSDiskCaching(CachingTypes.ReadWrite)
                    .WithOSDiskName("javatest")
                    .WithLicenseType("Windows_Server")
                    .Create();

                    IVirtualMachine foundVM = null;
                    var             vms     = computeManager.VirtualMachines.ListByResourceGroup(RGName);
                    foreach (IVirtualMachine vm1 in vms)
                    {
                        if (vm1.Name.Equals(VMName))
                        {
                            foundVM = vm1;
                            break;
                        }
                    }
                    Assert.NotNull(foundVM);
                    Assert.Equal(RegionPPG, foundVM.Region);
                    // Get
                    foundVM = computeManager.VirtualMachines.GetByResourceGroup(RGName, VMName);
                    Assert.NotNull(foundVM);
                    Assert.Equal(RegionPPG, foundVM.Region);
                    Assert.Equal("Windows_Server", foundVM.LicenseType);

                    // Fetch instance view
                    PowerState powerState = foundVM.PowerState;
                    Assert.Equal(powerState, PowerState.Running);
                    VirtualMachineInstanceView instanceView = foundVM.InstanceView;
                    Assert.NotNull(instanceView);
                    Assert.True(instanceView.Statuses.Count > 0);

                    Assert.NotNull(foundVM.ProximityPlacementGroup);
                    Assert.Equal(ProxyGroupType, foundVM.ProximityPlacementGroup.ProximityPlacementGroupType);
                    Assert.NotNull(foundVM.ProximityPlacementGroup.AvailabilitySetIds);
                    Assert.True(foundVM.ProximityPlacementGroup.AvailabilitySetIds.Count > 0);
                    Assert.Equal(setCreated.Id, foundVM.ProximityPlacementGroup.AvailabilitySetIds[0], true);
                    Assert.NotNull(foundVM.ProximityPlacementGroup.VirtualMachineIds);
                    Assert.True(foundVM.ProximityPlacementGroup.VirtualMachineIds.Count > 0);
                    Assert.Equal(foundVM.Id, setCreated.ProximityPlacementGroup.VirtualMachineIds[0], true);

                    //Update Vm to remove it from proximity placement group
                    IVirtualMachine updatedVm = foundVM.Update()
                                                .WithoutProximityPlacementGroup()
                                                .Apply();

                    Assert.NotNull(updatedVm.ProximityPlacementGroup);
                    Assert.Equal(ProxyGroupType, updatedVm.ProximityPlacementGroup.ProximityPlacementGroupType);
                    Assert.NotNull(updatedVm.ProximityPlacementGroup.AvailabilitySetIds);
                    Assert.True(updatedVm.ProximityPlacementGroup.AvailabilitySetIds.Count > 0);
                    Assert.Equal(setCreated.Id, updatedVm.ProximityPlacementGroup.AvailabilitySetIds[0], true);

                    //TODO: this does not work... can not remove cvm from the placement group
                    //Assert.assertNull(foundVM.proximityPlacementGroup().virtualMachineIds());

                    // Delete VM
                    computeManager.VirtualMachines.DeleteById(foundVM.Id);
                    computeManager.AvailabilitySets.DeleteById(setCreated.Id);
                }
                finally
                {
                    try
                    {
                        resourceManager.ResourceGroups.DeleteByName(RGName);
                    }
                    catch { }
                }
            }
        }
コード例 #15
0
        public void CannotUpdateProximityPlacementGroupForVirtualMachine()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                var GroupName1      = TestUtilities.GenerateName("rgfluentchash-");
                var GroupName2      = TestUtilities.GenerateName("rgfluentchash-");
                var AvailName1      = TestUtilities.GenerateName("availset1");
                var AvailName2      = TestUtilities.GenerateName("availset2");
                var ProxyGroupName1 = TestUtilities.GenerateName("testproxgroup1");
                var ProxyGroupName2 = TestUtilities.GenerateName("testproxgroup1");

                var ProxyGroupType = ProximityPlacementGroupType.Standard;
                var RegionPPG1     = Region.USWestCentral;
                var RegionPPG2     = Region.USSouthCentral;

                var computeManager  = TestHelper.CreateComputeManager();
                var resourceManager = TestHelper.CreateResourceManager();

                try
                {
                    var setCreated1 = computeManager.AvailabilitySets
                                      .Define(AvailName1)
                                      .WithRegion(RegionPPG1)
                                      .WithNewResourceGroup(GroupName1)
                                      .WithNewProximityPlacementGroup(ProxyGroupName1, ProxyGroupType)
                                      .Create();

                    Assert.Equal(AvailName1, setCreated1.Name);
                    Assert.NotNull(setCreated1.ProximityPlacementGroup);
                    Assert.Equal(ProxyGroupType, setCreated1.ProximityPlacementGroup.ProximityPlacementGroupType);
                    Assert.NotNull(setCreated1.ProximityPlacementGroup.AvailabilitySetIds);
                    Assert.False(setCreated1.ProximityPlacementGroup.AvailabilitySetIds.Count == 0);
                    Assert.Equal(setCreated1.Id, setCreated1.ProximityPlacementGroup.AvailabilitySetIds[0], true);
                    Assert.Equal(setCreated1.RegionName, setCreated1.ProximityPlacementGroup.Location);


                    var setCreated2 = computeManager.AvailabilitySets
                                      .Define(AvailName2)
                                      .WithRegion(RegionPPG2)
                                      .WithNewResourceGroup(GroupName2)
                                      .WithNewProximityPlacementGroup(ProxyGroupName2, ProxyGroupType)
                                      .Create();

                    Assert.Equal(AvailName2, setCreated2.Name);
                    Assert.NotNull(setCreated2.ProximityPlacementGroup);
                    Assert.Equal(ProxyGroupType, setCreated2.ProximityPlacementGroup.ProximityPlacementGroupType);
                    Assert.Equal(ProxyGroupType, setCreated2.ProximityPlacementGroup.ProximityPlacementGroupType);
                    Assert.NotNull(setCreated2.ProximityPlacementGroup.AvailabilitySetIds);
                    Assert.False(setCreated2.ProximityPlacementGroup.AvailabilitySetIds.Count == 0);
                    Assert.Equal(setCreated2.Id, setCreated2.ProximityPlacementGroup.AvailabilitySetIds[0], true);
                    Assert.Equal(setCreated2.RegionName, setCreated2.ProximityPlacementGroup.Location);

                    // Create
                    computeManager.VirtualMachines
                    .Define(VMName)
                    .WithRegion(RegionPPG1)
                    .WithExistingResourceGroup(GroupName1)
                    .WithNewPrimaryNetwork("10.0.0.0/28")
                    .WithPrimaryPrivateIPAddressDynamic()
                    .WithoutPrimaryPublicIPAddress()
                    .WithProximityPlacementGroup(setCreated1.ProximityPlacementGroup.Id)
                    .WithPopularWindowsImage(KnownWindowsVirtualMachineImage.WindowsServer2012Datacenter)
                    .WithAdminUsername("Foo12")
                    .WithAdminPassword("abc!@#F0orL")
                    .WithUnmanagedDisks()
                    .WithSize(VirtualMachineSizeTypes.StandardDS3V2)
                    .WithOSDiskCaching(CachingTypes.ReadWrite)
                    .WithOSDiskName("javatest")
                    .WithLicenseType("Windows_Server")
                    .Create();

                    IVirtualMachine foundVM = null;
                    var             vms     = computeManager.VirtualMachines.ListByResourceGroup(GroupName1);
                    foreach (IVirtualMachine vm1 in vms)
                    {
                        if (vm1.Name.Equals(VMName))
                        {
                            foundVM = vm1;
                            break;
                        }
                    }
                    Assert.NotNull(foundVM);
                    Assert.Equal(RegionPPG1, foundVM.Region);
                    // Get
                    foundVM = computeManager.VirtualMachines.GetByResourceGroup(GroupName1, VMName);
                    Assert.NotNull(foundVM);
                    Assert.Equal(RegionPPG1, foundVM.Region);
                    Assert.Equal("Windows_Server", foundVM.LicenseType);

                    // Fetch instance view
                    PowerState powerState = foundVM.PowerState;
                    Assert.Equal(powerState, PowerState.Running);
                    VirtualMachineInstanceView instanceView = foundVM.InstanceView;
                    Assert.NotNull(instanceView);
                    Assert.True(instanceView.Statuses.Count > 0);

                    Assert.NotNull(foundVM.ProximityPlacementGroup);
                    Assert.Equal(ProxyGroupType, foundVM.ProximityPlacementGroup.ProximityPlacementGroupType);
                    Assert.NotNull(foundVM.ProximityPlacementGroup.AvailabilitySetIds);
                    Assert.True(foundVM.ProximityPlacementGroup.AvailabilitySetIds.Count > 0);
                    Assert.Equal(setCreated1.Id, foundVM.ProximityPlacementGroup.AvailabilitySetIds[0], true);
                    Assert.NotNull(foundVM.ProximityPlacementGroup.VirtualMachineIds);
                    Assert.True(foundVM.ProximityPlacementGroup.VirtualMachineIds.Count > 0);
                    Assert.Equal(foundVM.Id, setCreated1.ProximityPlacementGroup.VirtualMachineIds[0], true);

                    try
                    {
                        //Update Vm to remove it from proximity placement group
                        IVirtualMachine updatedVm = foundVM.Update()
                                                    .WithProximityPlacementGroup(setCreated2.ProximityPlacementGroup.Id)
                                                    .Apply();
                    }
                    catch (Microsoft.Rest.Azure.CloudException clEx)
                    {
                        Assert.Equal("Changing property 'proximityPlacementGroup.id' is not allowed.", clEx.Message, true);
                    }

                    // Delete resources
                    computeManager.VirtualMachines.DeleteById(foundVM.Id);
                    computeManager.AvailabilitySets.DeleteById(setCreated1.Id);
                    computeManager.AvailabilitySets.DeleteById(setCreated2.Id);
                }
                finally
                {
                    try
                    {
                        resourceManager.ResourceGroups.DeleteByName(GroupName1);
                        resourceManager.ResourceGroups.DeleteByName(GroupName2);
                    }
                    catch { }
                }
            }
        }
コード例 #16
0
        public void CanCreate()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                var GroupName       = TestUtilities.GenerateName("rgfluentchash-");
                var computeManager  = TestHelper.CreateComputeManager();
                var resourceManager = TestHelper.CreateResourceManager();

                try
                {
                    // Create
                    var vm = computeManager.VirtualMachines
                             .Define(VMName)
                             .WithRegion(Location)
                             .WithNewResourceGroup(GroupName)
                             .WithNewPrimaryNetwork("10.0.0.0/28")
                             .WithPrimaryPrivateIPAddressDynamic()
                             .WithoutPrimaryPublicIPAddress()
                             .WithPopularWindowsImage(KnownWindowsVirtualMachineImage.WindowsServer2012Datacenter)
                             .WithAdminUsername("Foo12")
                             .WithAdminPassword("BaR@12!Foo")
                             .WithUnmanagedDisks()
                             .WithOSDiskCaching(CachingTypes.ReadWrite)
                             .WithSize(VirtualMachineSizeTypes.StandardD3)
                             .WithOSDiskName("javatest")
                             .Create();

                    var foundedVM = computeManager.VirtualMachines.ListByResourceGroup(GroupName)
                                    .FirstOrDefault(v => v.Name.Equals(VMName, StringComparison.OrdinalIgnoreCase));

                    Assert.NotNull(foundedVM);
                    Assert.Equal(Location, foundedVM.RegionName);
                    // Get
                    foundedVM = computeManager.VirtualMachines.GetByResourceGroup(GroupName, VMName);
                    Assert.NotNull(foundedVM);
                    Assert.Equal(Location, foundedVM.RegionName);

                    // Fetch instance view
                    PowerState powerState = foundedVM.PowerState;
                    Assert.True(powerState == PowerState.Running);
                    VirtualMachineInstanceView instanceView = foundedVM.InstanceView;
                    Assert.NotNull(instanceView);
                    Assert.NotEmpty(instanceView.Statuses);

                    // Capture the VM [Requires VM to be Poweroff and generalized]
                    foundedVM.PowerOff();
                    foundedVM.Generalize();
                    var jsonResult = foundedVM.Capture("captured-vhds", "cpt", true);
                    Assert.NotNull(jsonResult);

                    // Delete VM
                    computeManager.VirtualMachines.DeleteById(foundedVM.Id);
                }
                finally
                {
                    try
                    {
                        resourceManager.ResourceGroups.DeleteByName(GroupName);
                    }
                    catch { }
                }
            }
        }
 ///GENMHASH:56E00E1F789510BB94AFCDC1FF61D00B:C0B660115AA9DC53D76DEDA856496556
 internal VirtualMachineScaleSetVMImpl(VirtualMachineScaleSetVMInner inner, VirtualMachineScaleSetImpl parent)
     : base(inner, parent)
 {
     virtualMachineInstanceView = Inner.InstanceView;
 }
 ///GENMHASH:7F6A7E961EA5A11F2B8013E54123A7D0:C1CDD6BC19A1D800E2865E3DC44941E1
 private void ClearCachedRelatedResources()
 {
     this.virtualMachineInstanceView = null;
 }
コード例 #19
0
        private void SetNewExtension(VirtualMachine selectedVM, VirtualMachineInstanceView selectedVMStatus)
        {
            // check VM identity
            // give VM idenity access to resources/resource groups
            // deploy extension on VM

            //TODO should we allow user assigned identity?
            if (selectedVM.Identity == null)
            {
                selectedVM.Identity = new VirtualMachineIdentity(type: ResourceIdentityType.SystemAssigned);
                selectedVM          = this.ComputeClient.ComputeManagementClient.VirtualMachines.
                                      CreateOrUpdate(this.ResourceGroupName, this.VMName, selectedVM);
            }
            else if (selectedVM.Identity.Type == ResourceIdentityType.UserAssigned)
            {
                selectedVM.Identity.Type = ResourceIdentityType.SystemAssignedUserAssigned;
                selectedVM = this.ComputeClient.ComputeManagementClient.VirtualMachines.
                             CreateOrUpdate(this.ResourceGroupName, this.VMName, selectedVM);
            }

            HashSet <string> scopes = new HashSet <string>();

            int endIndex = 4; //Scope is set to resource group

            if (this.SetAccessToIndividualResources)
            {
                endIndex = 8; //Scope is set to resource
            }

            // Add VM Scope or Resource Group scope
            scopes.Add(String.Join("/", selectedVM.Id.Split('/').SubArray(0, endIndex)));
            //TODO: do we want to support unmanaged disks?
            scopes.Add(String.Join("/", selectedVM.StorageProfile.OsDisk.ManagedDisk.Id.Split('/').SubArray(0, endIndex)));
            foreach (var dataDisk in selectedVM.StorageProfile.DataDisks)
            {
                scopes.Add(String.Join("/", dataDisk.ManagedDisk.Id.Split('/').SubArray(0, endIndex)));
            }
            foreach (var nic in selectedVM.NetworkProfile.NetworkInterfaces)
            {
                scopes.Add(String.Join("/", nic.Id.Split('/').SubArray(0, endIndex)));
            }

            DateTime startTime = DateTime.Now;

            foreach (string scope in scopes)
            {
                /* In some cases, the role assignment cannot be created because the VM identity is not yet available for usage. */
                bool created = false;
                while (!created)
                {
                    string scopedRoleId            = $"{scope}/providers/Microsoft.Authorization/roleDefinitions/{AEMExtensionConstants.NewExtensionRole}";
                    string roleDefinitionId        = $"/subscriptions/{this.DefaultContext.Subscription.Id}/providers/Microsoft.Authorization/roleDefinitions/{AEMExtensionConstants.NewExtensionRole}";
                    var    existingRoleAssignments = AuthClient.RoleAssignments.ListForScope(scope);
                    var    existingRoleAssignment  = existingRoleAssignments.FirstOrDefault(assignmentTest =>
                                                                                            assignmentTest.Properties.PrincipalId.EqualsInsensitively(selectedVM.Identity.PrincipalId) &&
                                                                                            assignmentTest.Properties.RoleDefinitionId.EqualsInsensitively(roleDefinitionId) &&
                                                                                            assignmentTest.Properties.Scope.EqualsInsensitively(scope));

                    if (existingRoleAssignment != null)
                    {
                        this._Helper.WriteVerbose($"Role Assignment for scope {scope} already exists for principal {selectedVM.Identity.PrincipalId}");
                        created = true;
                        break;
                    }


                    RoleAssignmentCreateParameters createParameters = new RoleAssignmentCreateParameters()
                    {
                        Properties = new RoleAssignmentProperties()
                        {
                            RoleDefinitionId = scopedRoleId,
                            //TODO: do we want to support user assigned identity?
                            PrincipalId = selectedVM.Identity.PrincipalId
                        }
                    };
                    try
                    {
                        string testMode       = Environment.GetEnvironmentVariable("AZURE_TEST_MODE");
                        string assignmentName = Guid.NewGuid().ToString();
                        if ("Record".EqualsInsensitively(testMode) || Microsoft.WindowsAzure.Commands.Utilities.Common.TestMockSupport.RunningMocked)
                        {
                            // Make sure to use the same ID during test record and playback
                            assignmentName = AEMHelper.GenerateGuid(scope);
                        }

                        AuthClient.RoleAssignments.Create(scope, assignmentName, createParameters);
                        created = true;
                    }
                    catch (CloudException cex)
                    {
                        if (!("PrincipalNotFound".Equals(cex.Body.Code)))
                        {
                            throw;
                        }

                        this._Helper.WriteVerbose(cex.ToString());
                    }

                    if (!created && (DateTime.Now - startTime).TotalSeconds < MAX_WAIT_TIME_FOR_SP_SECONDS)
                    {
                        this._Helper.WriteVerbose("Virtual Machine System Identity not available yet - waiting 5 seconds");
                        Microsoft.WindowsAzure.Commands.Utilities.Common.TestMockSupport.Delay(5000);
                    }
                    else if (!created)
                    {
                        this._Helper.WriteError($"Waited {MAX_WAIT_TIME_FOR_SP_SECONDS} seconds for VM identity to become available - giving up. Please try again later.");
                        return;
                    }
                }
            }

            var sapmonPublicConfig = new List <KeyValuePair>();

            if (!String.IsNullOrEmpty(this.ProxyURI))
            {
                sapmonPublicConfig.Add(new KeyValuePair()
                {
                    Key = "proxy", Value = this.ProxyURI
                });
            }
            if (this.DebugExtension.IsPresent)
            {
                sapmonPublicConfig.Add(new KeyValuePair()
                {
                    Key = "debug", Value = "1"
                });
            }

            ExtensionConfig jsonPublicConfig = new ExtensionConfig();

            jsonPublicConfig.Config = sapmonPublicConfig;

            var vmExtensionConfig = new VirtualMachineExtension()
            {
                Publisher = AEMExtensionConstants.AEMExtensionPublisherv2[OSType],
                VirtualMachineExtensionType = AEMExtensionConstants.AEMExtensionTypev2[OSType],
                TypeHandlerVersion          = AEMExtensionConstants.AEMExtensionVersionv2[OSType].ToString(2),
                Location = selectedVM.Location,
                Settings = jsonPublicConfig,
                AutoUpgradeMinorVersion = true,
                ForceUpdateTag          = DateTime.Now.Ticks.ToString()
            };

            if (NoWait.IsPresent)
            {
                var op = this.VirtualMachineExtensionClient.BeginCreateOrUpdateWithHttpMessagesAsync(
                    this.ResourceGroupName, this.VMName, AEMExtensionConstants.AEMExtensionDefaultNamev2[OSType],
                    vmExtensionConfig).GetAwaiter().GetResult();

                var result = ComputeAutoMapperProfile.Mapper.Map <PSAzureOperationResponse>(op);
                WriteObject(result);
            }
            else
            {
                var op = this.VirtualMachineExtensionClient.CreateOrUpdateWithHttpMessagesAsync(
                    this.ResourceGroupName, this.VMName, AEMExtensionConstants.AEMExtensionDefaultNamev2[OSType],
                    vmExtensionConfig).GetAwaiter().GetResult();

                var result = ComputeAutoMapperProfile.Mapper.Map <PSAzureOperationResponse>(op);
                WriteObject(result);
            }
        }
コード例 #20
0
        private void SetOldExtension(VirtualMachine selectedVM, VirtualMachineInstanceView selectedVMStatus)
        {
            var osdisk = selectedVM.StorageProfile.OsDisk;
            var disks  = selectedVM.StorageProfile.DataDisks;

            var sapmonPublicConfig  = new List <KeyValuePair>();
            var sapmonPrivateConfig = new List <KeyValuePair>();
            var cpuOvercommit       = 0;
            var memOvercommit       = 0;
            var vmsize = selectedVM.HardwareProfile.VmSize;

            switch (vmsize)
            {
            case AEMExtensionConstants.VMSizeExtraSmall:
            case AEMExtensionConstants.VMSizeStandard_A0:
            case AEMExtensionConstants.VMSizeBasic_A0:
                vmsize = "ExtraSmall (A0)";
                WriteVerbose("VM Size is ExtraSmall - setting overcommitted setting");
                cpuOvercommit = 1;
                break;

            case "Small":
                vmsize = "Small (A1)";
                break;

            case "Medium":
                vmsize = "Medium (A2)";
                break;

            case "Large":
                vmsize = "Large (A3)";
                break;

            case "ExtraLarge":
                vmsize = "ExtraLarge (A4)";
                break;
            }
            sapmonPublicConfig.Add(new KeyValuePair()
            {
                Key = "vmsize", Value = vmsize
            });
            sapmonPublicConfig.Add(new KeyValuePair()
            {
                Key = "vm.role", Value = "IaaS"
            });
            sapmonPublicConfig.Add(new KeyValuePair()
            {
                Key = "vm.memory.isovercommitted", Value = memOvercommit
            });
            sapmonPublicConfig.Add(new KeyValuePair()
            {
                Key = "vm.cpu.isovercommitted", Value = cpuOvercommit
            });
            sapmonPublicConfig.Add(new KeyValuePair()
            {
                Key = "script.version", Value = AEMExtensionConstants.CurrentScriptVersion
            });
            sapmonPublicConfig.Add(new KeyValuePair()
            {
                Key = "verbose", Value = "0"
            });
            sapmonPublicConfig.Add(new KeyValuePair()
            {
                Key = "href", Value = "http://aka.ms/sapaem"
            });

            var vmSLA = this._Helper.GetVMSLA(selectedVM);

            if (vmSLA.HasSLA)
            {
                sapmonPublicConfig.Add(new KeyValuePair()
                {
                    Key = "vm.sla.throughput", Value = vmSLA.TP
                });
                sapmonPublicConfig.Add(new KeyValuePair()
                {
                    Key = "vm.sla.iops", Value = vmSLA.IOPS
                });
            }

            // Get Disks
            var accounts = new Dictionary <string, string>(StringComparer.InvariantCultureIgnoreCase);

            if (osdisk.ManagedDisk == null)
            {
                var accountName = this._Helper.GetStorageAccountFromUri(osdisk.Vhd.Uri);
                var storageKey  = this._Helper.GetAzureStorageKeyFromCache(accountName);
                accounts.Add(accountName, storageKey);

                this._Helper.WriteHost("[INFO] Adding configuration for OS disk");

                var caching = osdisk.Caching;
                sapmonPublicConfig.Add(new KeyValuePair()
                {
                    Key = "osdisk.name", Value = this._Helper.GetDiskName(osdisk.Vhd.Uri)
                });
                sapmonPublicConfig.Add(new KeyValuePair()
                {
                    Key = "osdisk.caching", Value = caching
                });
                sapmonPublicConfig.Add(new KeyValuePair()
                {
                    Key = "osdisk.account", Value = accountName
                });
                if (this._Helper.IsPremiumStorageAccount(accountName))
                {
                    WriteVerbose("OS Disk Storage Account is a premium account - adding SLAs for OS disk");
                    var sla = this._Helper.GetDiskSLA(osdisk);
                    sapmonPublicConfig.Add(new KeyValuePair()
                    {
                        Key = "osdisk.type", Value = AEMExtensionConstants.DISK_TYPE_PREMIUM
                    });
                    sapmonPublicConfig.Add(new KeyValuePair()
                    {
                        Key = "osdisk.sla.throughput", Value = sla.TP
                    });
                    sapmonPublicConfig.Add(new KeyValuePair()
                    {
                        Key = "osdisk.sla.iops", Value = sla.IOPS
                    });
                }
                else
                {
                    WriteVerbose("OS Disk Storage Account is a standard account");
                    sapmonPublicConfig.Add(new KeyValuePair()
                    {
                        Key = "osdisk.type", Value = AEMExtensionConstants.DISK_TYPE_STANDARD
                    });
                    sapmonPublicConfig.Add(new KeyValuePair()
                    {
                        Key = "osdisk.connminute", Value = (accountName + ".minute")
                    });
                    sapmonPublicConfig.Add(new KeyValuePair()
                    {
                        Key = "osdisk.connhour", Value = (accountName + ".hour")
                    });
                }
            }
            else
            {
                var resId = new ResourceIdentifier(osdisk.ManagedDisk.Id);

                var osDiskMD = ComputeClient.ComputeManagementClient.Disks.Get(resId.ResourceGroupName, resId.ResourceName);
                if (osDiskMD.Sku.Name == StorageAccountTypes.PremiumLRS)
                {
                    WriteVerbose("OS Disk is a Premium Managed Disk - adding SLAs for OS disk");
                    var sla     = this._Helper.GetDiskSLA(osDiskMD.DiskSizeGB, null);
                    var caching = osdisk.Caching;
                    sapmonPublicConfig.Add(new KeyValuePair()
                    {
                        Key = "osdisk.name", Value = resId.ResourceName
                    });
                    sapmonPublicConfig.Add(new KeyValuePair()
                    {
                        Key = "osdisk.caching", Value = caching
                    });
                    sapmonPublicConfig.Add(new KeyValuePair()
                    {
                        Key = "osdisk.type", Value = AEMExtensionConstants.DISK_TYPE_PREMIUM_MD
                    });
                    sapmonPublicConfig.Add(new KeyValuePair()
                    {
                        Key = "osdisk.sla.throughput", Value = sla.TP
                    });
                    sapmonPublicConfig.Add(new KeyValuePair()
                    {
                        Key = "osdisk.sla.iops", Value = sla.IOPS
                    });
                }
                else
                {
                    this._Helper.WriteWarning("[WARN] Standard Managed Disks are not supported. Extension will be installed but no disk metrics will be available.");
                }
            }

            // Get Storage accounts from disks
            var diskNumber = 1;

            foreach (var disk in disks)
            {
                if (disk.ManagedDisk != null)
                {
                    var resId = new ResourceIdentifier(disk.ManagedDisk.Id);

                    var diskMD = ComputeClient.ComputeManagementClient.Disks.Get(resId.ResourceGroupName, resId.ResourceName);

                    if (diskMD.Sku.Name == StorageAccountTypes.PremiumLRS)
                    {
                        this._Helper.WriteVerbose("Data Disk {0} is a Premium Managed Disk - adding SLAs for disk", diskNumber.ToString());
                        var sla       = this._Helper.GetDiskSLA(diskMD.DiskSizeGB, null);
                        var cachingMD = disk.Caching;
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = "disk.lun." + diskNumber, Value = disk.Lun
                        });
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = "disk.name." + diskNumber, Value = resId.ResourceName
                        });
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = "disk.caching." + diskNumber, Value = cachingMD
                        });
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = "disk.type." + diskNumber, Value = AEMExtensionConstants.DISK_TYPE_PREMIUM_MD
                        });
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = "disk.sla.throughput." + diskNumber, Value = sla.TP
                        });
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = "disk.sla.iops." + diskNumber, Value = sla.IOPS
                        });
                        this._Helper.WriteVerbose("Done - Data Disk {0} is a Premium Managed Disk - adding SLAs for disk", diskNumber.ToString());
                    }
                    else if (diskMD.Sku.Name == StorageAccountTypes.UltraSSDLRS)
                    {
                        this._Helper.WriteVerbose("Data Disk {0} is an UltraSSD Disk - adding SLAs for disk", diskNumber.ToString());
                        var sla       = this._Helper.GetDiskSLA(diskMD.DiskSizeGB, null);
                        var cachingMD = disk.Caching;
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = "disk.lun." + diskNumber, Value = disk.Lun
                        });
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = "disk.name." + diskNumber, Value = resId.ResourceName
                        });
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = "disk.caching." + diskNumber, Value = cachingMD
                        });
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = "disk.type." + diskNumber, Value = AEMExtensionConstants.DISK_TYPE_ULTRA_MD
                        });
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = "disk.sla.throughput." + diskNumber, Value = diskMD.DiskMBpsReadWrite
                        });
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = "disk.sla.iops." + diskNumber, Value = diskMD.DiskIOPSReadWrite
                        });
                        this._Helper.WriteVerbose("Done - Data Disk {0} is an UltraSSD Disk - adding SLAs for disk", diskNumber.ToString());
                    }
                    else
                    {
                        this._Helper.WriteWarning("[WARN] Standard Managed Disks are not supported. Extension will be installed but no disk metrics will be available.");
                    }
                }
                else
                {
                    var accountName = this._Helper.GetStorageAccountFromUri(disk.Vhd.Uri);
                    if (!accounts.ContainsKey(accountName))
                    {
                        var storageKey = this._Helper.GetAzureStorageKeyFromCache(accountName);
                        accounts.Add(accountName, storageKey);
                    }

                    this._Helper.WriteHost("[INFO] Adding configuration for data disk {0}", disk.Name);
                    var caching = disk.Caching;
                    sapmonPublicConfig.Add(new KeyValuePair()
                    {
                        Key = "disk.lun." + diskNumber, Value = disk.Lun
                    });
                    sapmonPublicConfig.Add(new KeyValuePair()
                    {
                        Key = "disk.name." + diskNumber, Value = this._Helper.GetDiskName(disk.Vhd.Uri)
                    });
                    sapmonPublicConfig.Add(new KeyValuePair()
                    {
                        Key = "disk.caching." + diskNumber, Value = caching
                    });
                    sapmonPublicConfig.Add(new KeyValuePair()
                    {
                        Key = "disk.account." + diskNumber, Value = accountName
                    });

                    if (this._Helper.IsPremiumStorageAccount(accountName))
                    {
                        this._Helper.WriteVerbose("Data Disk {0} Storage Account is a premium account - adding SLAs for disk", diskNumber.ToString());
                        var sla = this._Helper.GetDiskSLA(disk);
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = "disk.type." + diskNumber, Value = AEMExtensionConstants.DISK_TYPE_PREMIUM
                        });
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = "disk.sla.throughput." + diskNumber, Value = sla.TP
                        });
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = "disk.sla.iops." + diskNumber, Value = sla.IOPS
                        });
                        this._Helper.WriteVerbose("Done - Data Disk {0} Storage Account is a premium account - adding SLAs for disk", diskNumber.ToString());
                    }
                    else
                    {
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = "disk.type." + diskNumber, Value = AEMExtensionConstants.DISK_TYPE_STANDARD
                        });
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = "disk.connminute." + diskNumber, Value = (accountName + ".minute")
                        });
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = "disk.connhour." + diskNumber, Value = (accountName + ".hour")
                        });
                    }
                }
                diskNumber += 1;
            }

            //Check storage accounts for analytics
            foreach (var account in accounts)
            {
                this._Helper.WriteVerbose("Testing Storage Metrics for {0}", account.Key);

                var storage = this._Helper.GetStorageAccountFromCache(account.Key);

                if (!this._Helper.IsPremiumStorageAccount(storage))
                {
                    if (!this.SkipStorage.IsPresent)
                    {
                        var currentConfig = this._Helper.GetStorageAnalytics(storage.Name);

                        if (!this._Helper.CheckStorageAnalytics(storage.Name, currentConfig))
                        {
                            this._Helper.WriteHost("[INFO] Enabling Storage Account Metrics for storage account {0}", storage.Name);

                            // Enable analytics on storage accounts
                            this.SetStorageAnalytics(storage.Name);
                        }
                    }

                    var endpoint  = this._Helper.GetAzureSAPTableEndpoint(storage);
                    var hourUri   = endpoint + "$MetricsHourPrimaryTransactionsBlob";
                    var minuteUri = endpoint + "$MetricsMinutePrimaryTransactionsBlob";

                    this._Helper.WriteHost("[INFO] Adding Storage Account Metric information for storage account {0}", storage.Name);

                    sapmonPrivateConfig.Add(new KeyValuePair()
                    {
                        Key = ((storage.Name) + ".hour.key"), Value = account.Value
                    });
                    sapmonPrivateConfig.Add(new KeyValuePair()
                    {
                        Key = ((storage.Name) + ".minute.key"), Value = account.Value
                    });
                    sapmonPublicConfig.Add(new KeyValuePair()
                    {
                        Key = ((storage.Name) + ".hour.uri"), Value = hourUri
                    });
                    sapmonPublicConfig.Add(new KeyValuePair()
                    {
                        Key = ((storage.Name) + ".minute.uri"), Value = minuteUri
                    });
                    sapmonPublicConfig.Add(new KeyValuePair()
                    {
                        Key = ((storage.Name) + ".hour.name"), Value = storage.Name
                    });
                    sapmonPublicConfig.Add(new KeyValuePair()
                    {
                        Key = ((storage.Name) + ".minute.name"), Value = storage.Name
                    });
                }
                else
                {
                    this._Helper.WriteHost("[INFO] {0} is of type {1} - Storage Account Metrics are not available for Premium Type Storage.", storage.Name, storage.SkuName());
                    sapmonPublicConfig.Add(new KeyValuePair()
                    {
                        Key = ((storage.Name) + ".hour.ispremium"), Value = 1
                    });
                    sapmonPublicConfig.Add(new KeyValuePair()
                    {
                        Key = ((storage.Name) + ".minute.ispremium"), Value = 1
                    });
                }
            }

            WriteVerbose("Chechking if WAD needs to be configured");
            // Enable VM Diagnostics
            if (this.EnableWAD.IsPresent)
            {
                this._Helper.WriteHost("[INFO] Enabling IaaSDiagnostics for VM {0}", selectedVM.Name);
                KeyValuePair wadstorage = null;
                if (String.IsNullOrEmpty(this.WADStorageAccountName))
                {
                    KeyValuePair <string, string>?wadstorageTemp = accounts.Cast <KeyValuePair <string, string>?>().
                                                                   FirstOrDefault(accTemp => !this._Helper.IsPremiumStorageAccount(accTemp.Value.Key));
                    if (wadstorageTemp.HasValue)
                    {
                        wadstorage = new KeyValuePair(wadstorageTemp.Value.Key, wadstorageTemp.Value.Value);
                    }
                }
                else
                {
                    wadstorage = new KeyValuePair(this.WADStorageAccountName, this._Helper.GetAzureStorageKeyFromCache(WADStorageAccountName));
                }

                if (wadstorage == null)
                {
                    this._Helper.WriteError("A standard storage account is required. Please use parameter WADStorageAccountName to specify a standard storage account you want to use for this VM.");
                    return;
                }

                selectedVM = SetAzureVMDiagnosticsExtensionC(selectedVM, selectedVMStatus, wadstorage.Key, wadstorage.Value as string);

                var storage  = this._Helper.GetStorageAccountFromCache(wadstorage.Key);
                var endpoint = this._Helper.GetAzureSAPTableEndpoint(storage);
                var wadUri   = endpoint + AEMExtensionConstants.WadTableName;

                sapmonPrivateConfig.Add(new KeyValuePair()
                {
                    Key = "wad.key", Value = wadstorage.Value
                });
                sapmonPublicConfig.Add(new KeyValuePair()
                {
                    Key = "wad.name", Value = wadstorage.Key
                });
                sapmonPublicConfig.Add(new KeyValuePair()
                {
                    Key = "wad.isenabled", Value = 1
                });
                sapmonPublicConfig.Add(new KeyValuePair()
                {
                    Key = "wad.uri", Value = wadUri
                });
            }
            else
            {
                sapmonPublicConfig.Add(new KeyValuePair()
                {
                    Key = "wad.isenabled", Value = 0
                });
            }

            ExtensionConfig jsonPublicConfig = new ExtensionConfig();

            jsonPublicConfig.Config = sapmonPublicConfig;

            ExtensionConfig jsonPrivateConfig = new ExtensionConfig();

            jsonPrivateConfig.Config = sapmonPrivateConfig;

            this._Helper.WriteHost("[INFO] Updating Azure Enhanced Monitoring Extension for SAP configuration - Please wait...");

            WriteVerbose("Installing AEM extension");

            Version aemVersion = this._Helper.GetExtensionVersion(selectedVM, selectedVMStatus, OSType, AEMExtensionConstants.AEMExtensionType[OSType], AEMExtensionConstants.AEMExtensionPublisher[OSType]);

            if (NoWait.IsPresent)
            {
                var op = this.VirtualMachineExtensionClient.BeginCreateOrUpdateWithHttpMessagesAsync(
                    this.ResourceGroupName, this.VMName, AEMExtensionConstants.AEMExtensionDefaultName[OSType],
                    new VirtualMachineExtension()
                {
                    Publisher = AEMExtensionConstants.AEMExtensionPublisher[OSType],
                    VirtualMachineExtensionType = AEMExtensionConstants.AEMExtensionType[OSType],
                    TypeHandlerVersion          = aemVersion.ToString(2),
                    Settings                = jsonPublicConfig,
                    ProtectedSettings       = jsonPrivateConfig,
                    Location                = selectedVM.Location,
                    AutoUpgradeMinorVersion = true,
                    ForceUpdateTag          = DateTime.Now.Ticks.ToString()
                }).GetAwaiter().GetResult();

                this._Helper.WriteHost("[INFO] Azure Enhanced Monitoring Extension for SAP configuration updated. It can take up to 15 Minutes for the monitoring data to appear in the SAP system.");
                this._Helper.WriteHost("[INFO] You can check the configuration of a virtual machine by calling the Test-AzVMAEMExtension commandlet.");

                var result = ComputeAutoMapperProfile.Mapper.Map <PSAzureOperationResponse>(op);
                WriteObject(result);
            }
            else
            {
                var op = this.VirtualMachineExtensionClient.CreateOrUpdateWithHttpMessagesAsync(
                    this.ResourceGroupName, this.VMName, AEMExtensionConstants.AEMExtensionDefaultName[OSType],
                    new VirtualMachineExtension()
                {
                    Publisher = AEMExtensionConstants.AEMExtensionPublisher[OSType],
                    VirtualMachineExtensionType = AEMExtensionConstants.AEMExtensionType[OSType],
                    TypeHandlerVersion          = aemVersion.ToString(2),
                    Settings                = jsonPublicConfig,
                    ProtectedSettings       = jsonPrivateConfig,
                    Location                = selectedVM.Location,
                    AutoUpgradeMinorVersion = true,
                    ForceUpdateTag          = DateTime.Now.Ticks.ToString()
                }).GetAwaiter().GetResult();

                this._Helper.WriteHost("[INFO] Azure Enhanced Monitoring Extension for SAP configuration updated. It can take up to 15 Minutes for the monitoring data to appear in the SAP system.");
                this._Helper.WriteHost("[INFO] You can check the configuration of a virtual machine by calling the Test-AzVMAEMExtension commandlet.");

                var result = ComputeAutoMapperProfile.Mapper.Map <PSAzureOperationResponse>(op);
                WriteObject(result);
            }
        }
コード例 #21
0
        private AzureDiskEncryptionStatusContext GetStatusFromInstanceView(VirtualMachine vm)
        {
            AzureDiskEncryptionStatusContext result = new AzureDiskEncryptionStatusContext();

            result.OsVolumeEncrypted    = EncryptionStatus.Unknown;
            result.DataVolumesEncrypted = EncryptionStatus.Unknown;

            StorageProfile             storageProfile = vm.StorageProfile;
            VirtualMachineInstanceView iv             = vm.InstanceView;

            if (iv != null)
            {
                result.OsVolumeEncrypted    = EncryptionStatus.NoDiskFound;
                result.DataVolumesEncrypted = EncryptionStatus.NoDiskFound;

                foreach (DiskInstanceView div in iv.Disks)
                {
                    if (div.Name.Equals(storageProfile.OsDisk.Name))
                    {
                        // check os volume status
                        string status = GetLastEncryptionStatus(div);
                        switch (status)
                        {
                        case "EncryptionState/encrypted":
                            result.OsVolumeEncrypted = EncryptionStatus.Encrypted;
                            break;

                        case "EncryptionState/notEncrypted":
                        case "":
                            result.OsVolumeEncrypted = EncryptionStatus.NotEncrypted;
                            break;

                        default:
                            break;
                        }
                        result.OsVolumeEncryptionSettings = (div.EncryptionSettings != null) ? div.EncryptionSettings[0] : null;
                    }
                    else
                    {
                        // check data volume status

                        // Mark DataVolumesEncrypted as Encrypted if even one of the disks is Encrypted
                        // Skip if DataVolumesEncrypted has already been marked Encrypted
                        if (result.DataVolumesEncrypted == EncryptionStatus.Encrypted)
                        {
                            continue;
                        }

                        string status = GetLastEncryptionStatus(div);
                        switch (status)
                        {
                        case "EncryptionState/encrypted":
                            result.DataVolumesEncrypted = EncryptionStatus.Encrypted;
                            break;

                        case "EncryptionState/notEncrypted":
                        case "":
                            result.DataVolumesEncrypted = EncryptionStatus.NotEncrypted;
                            break;

                        default:
                            break;
                        }
                    }
                }
            }

            return(result);
        }
コード例 #22
0
        private List <AEMTestResult> TestOldExtension(VirtualMachine selectedVM, VirtualMachineInstanceView selectedVMStatus, VirtualMachineExtension monExtension)
        {
            var osdisk = selectedVM.StorageProfile.OsDisk;
            List <AEMTestResult> partialResults = new List <AEMTestResult>();

            this._Helper.WriteHost("Azure Enhanced Monitoring Extension for SAP Installation check...", false);

            string monPublicConfig = null;

            if (monExtension != null)
            {
                monPublicConfig = monExtension.Settings.ToString();
            }

            if (monExtension == null || String.IsNullOrEmpty(monPublicConfig))
            {
                partialResults.Add(new AEMTestResult("Azure Enhanced Monitoring Extension for SAP Installation check", false));
                this._Helper.WriteHost("NOT OK ", ConsoleColor.Red);
            }
            else
            {
                partialResults.Add(new AEMTestResult("Azure Enhanced Monitoring Extension for SAP Installation check", true));
                this._Helper.WriteHost("OK ", ConsoleColor.Green);
            }
            //#################################################
            //#################################################

            var accounts = new List <string>();
            //var osdisk = selectedVM.StorageProfile.OsDisk;

            var osaccountName = String.Empty;

            if (osdisk.ManagedDisk == null)
            {
                var accountName = this._Helper.GetStorageAccountFromUri(osdisk.Vhd.Uri);
                osaccountName = accountName;
                accounts.Add(accountName);
            }

            var dataDisks = selectedVM.StorageProfile.DataDisks;

            foreach (var disk in dataDisks)
            {
                if (disk.ManagedDisk != null)
                {
                    continue;
                }
                var accountName = this._Helper.GetStorageAccountFromUri(disk.Vhd.Uri);
                if (!accounts.Contains(accountName))
                {
                    accounts.Add(accountName);
                }
            }

            //#################################################
            //# Check storage metrics
            //#################################################
            this._Helper.WriteHost("Storage Metrics check...");
            var metricsResult = new AEMTestResult("Storage Metrics check");

            partialResults.Add(metricsResult);
            if (!this.SkipStorageCheck.IsPresent)
            {
                foreach (var account in accounts)
                {
                    var accountResult = new AEMTestResult("Storage Metrics check for {0}", account);
                    metricsResult.PartialResults.Add(accountResult);

                    this._Helper.WriteHost("\tStorage Metrics check for {0}...", account);
                    var storage = this._Helper.GetStorageAccountFromCache(account);

                    if (!this._Helper.IsPremiumStorageAccount(storage))
                    {
                        this._Helper.WriteHost("\t\tStorage Metrics configuration check for {0}...", false, account);
                        var currentConfig = this._Helper.GetStorageAnalytics(account);

                        bool storageConfigOk = false;
                        if (!this._Helper.CheckStorageAnalytics(account, currentConfig))
                        {
                            accountResult.PartialResults.Add(new AEMTestResult("Storage Metrics configuration check for {0}", false, account));
                            this._Helper.WriteHost("NOT OK ", ConsoleColor.Red);
                        }
                        else
                        {
                            accountResult.PartialResults.Add(new AEMTestResult("Storage Metrics configuration check for {0}", true, account));
                            this._Helper.WriteHost("OK ", ConsoleColor.Green);
                            storageConfigOk = true;
                        }

                        this._Helper.WriteHost("\t\tStorage Metrics data check for {0}...", false, account);
                        var filterMinute = Microsoft.WindowsAzure.Storage.Table.TableQuery.
                                           GenerateFilterConditionForDate("Timestamp", "gt", DateTime.Now.AddMinutes(AEMExtensionConstants.ContentAgeInMinutes * -1));

                        if (storageConfigOk && this._Helper.CheckTableAndContent(account, "$MetricsMinutePrimaryTransactionsBlob", filterMinute, ".", false, this.WaitTimeInMinutes))

                        {
                            this._Helper.WriteHost("OK ", ConsoleColor.Green);
                            accountResult.PartialResults.Add(new AEMTestResult("Storage Metrics data check for {0}", true, account));
                        }
                        else
                        {
                            accountResult.PartialResults.Add(new AEMTestResult("Storage Metrics data check for {0}", false, account));
                            this._Helper.WriteHost("NOT OK ", ConsoleColor.Red);
                        }
                    }
                    else
                    {
                        accountResult.PartialResults.Add(new AEMTestResult("Storage Metrics not available for Premium Storage account {0}", true, account));
                        this._Helper.WriteHost("\t\tStorage Metrics not available for Premium Storage account {0}...", false, account);
                        this._Helper.WriteHost("OK ", ConsoleColor.Green);
                    }
                }
                if (accounts.Count == 0)
                {
                    metricsResult.Result = true;
                }
            }
            else
            {
                metricsResult.Result = true;
                this._Helper.WriteHost("Skipped ", ConsoleColor.Yellow);
            }
            //#################################################
            //#################################################


            //#################################################
            //# Check Azure Enhanced Monitoring Extension for SAP Configuration
            //#################################################
            this._Helper.WriteHost("Azure Enhanced Monitoring Extension for SAP public configuration check...", false);
            var aemConfigResult = new AEMTestResult("Azure Enhanced Monitoring Extension for SAP public configuration check");

            partialResults.Add(aemConfigResult);

            JObject sapmonPublicConfig = null;

            if (monExtension != null)
            {
                this._Helper.WriteHost(""); //New Line

                sapmonPublicConfig = JsonConvert.DeserializeObject(monPublicConfig) as JObject;

                StorageAccount storage            = null;
                var            osaccountIsPremium = false;
                if (!String.IsNullOrEmpty(osaccountName))
                {
                    storage            = this._Helper.GetStorageAccountFromCache(osaccountName);
                    osaccountIsPremium = this._Helper.IsPremiumStorageAccount(osaccountName);
                }

                var vmSize = selectedVM.HardwareProfile.VmSize;
                this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM Size", "vmsize", sapmonPublicConfig, vmSize.ToString(), aemConfigResult);
                this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM Memory", "vm.memory.isovercommitted", sapmonPublicConfig, 0, aemConfigResult);
                this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM CPU", "vm.cpu.isovercommitted", sapmonPublicConfig, 0, aemConfigResult);
                this._Helper.MonitoringPropertyExists("Azure Enhanced Monitoring Extension for SAP public configuration check: Script Version", "script.version", sapmonPublicConfig, aemConfigResult);

                var vmSLA = this._Helper.GetVMSLA(selectedVM);
                if (vmSLA.HasSLA)
                {
                    this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM SLA IOPS", "vm.sla.iops", sapmonPublicConfig, vmSLA.IOPS, aemConfigResult);
                    this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM SLA Throughput", "vm.sla.throughput", sapmonPublicConfig, vmSLA.TP, aemConfigResult);
                }

                int wadEnabled;
                if (this._Helper.GetMonPropertyValue("wad.isenabled", sapmonPublicConfig, out wadEnabled))
                {
                    if (wadEnabled == 1)
                    {
                        this._Helper.MonitoringPropertyExists("Azure Enhanced Monitoring Extension for SAP public configuration check: WAD name", "wad.name", sapmonPublicConfig, aemConfigResult);
                        this._Helper.MonitoringPropertyExists("Azure Enhanced Monitoring Extension for SAP public configuration check: WAD URI", "wad.uri", sapmonPublicConfig, aemConfigResult);
                    }
                    else
                    {
                        this._Helper.MonitoringPropertyExists("Azure Enhanced Monitoring Extension for SAP public configuration check: WAD name", "wad.name", sapmonPublicConfig, aemConfigResult, false);
                        this._Helper.MonitoringPropertyExists("Azure Enhanced Monitoring Extension for SAP public configuration check: WAD URI", "wad.uri", sapmonPublicConfig, aemConfigResult, false);
                    }
                }
                else
                {
                    string message = "Azure Enhanced Monitoring Extension for SAP public configuration check:";
                    aemConfigResult.PartialResults.Add(new AEMTestResult(message, false));
                    this._Helper.WriteHost(message + "...", false);
                    this._Helper.WriteHost("NOT OK ", ConsoleColor.Red);
                }

                if (!osaccountIsPremium && storage != null)
                {
                    var endpoint  = this._Helper.GetAzureSAPTableEndpoint(storage);
                    var minuteUri = endpoint + "$MetricsMinutePrimaryTransactionsBlob";

                    this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM OS disk URI Key", "osdisk.connminute", sapmonPublicConfig, osaccountName + ".minute", aemConfigResult);
                    //# TODO: check uri config
                    this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM OS disk URI Value", osaccountName + ".minute.uri", sapmonPublicConfig, minuteUri, aemConfigResult);
                    this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM OS disk URI Name", osaccountName + ".minute.name", sapmonPublicConfig, osaccountName, aemConfigResult);
                    this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM OS Disk Type", "osdisk.type", sapmonPublicConfig, AEMExtensionConstants.DISK_TYPE_STANDARD, aemConfigResult);
                }
                else if (storage != null)
                {
                    var sla = this._Helper.GetDiskSLA(osdisk);

                    this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM OS Disk Type", "osdisk.type", sapmonPublicConfig, AEMExtensionConstants.DISK_TYPE_PREMIUM, aemConfigResult);
                    this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM OS Disk SLA IOPS", "osdisk.sla.throughput", sapmonPublicConfig, sla.TP, aemConfigResult);
                    this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM OS Disk SLA Throughput", "osdisk.sla.iops", sapmonPublicConfig, sla.IOPS, aemConfigResult);
                }
                else
                {
                    var resId = new ResourceIdentifier(osdisk.ManagedDisk.Id);

                    var osDiskMD = ComputeClient.ComputeManagementClient.Disks.Get(resId.ResourceGroupName, resId.ResourceName);
                    if (osDiskMD.Sku.Name == StorageAccountTypes.PremiumLRS)
                    {
                        var sla = this._Helper.GetDiskSLA(osDiskMD.DiskSizeGB, null);

                        this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM OS Disk Type", "osdisk.type", sapmonPublicConfig, AEMExtensionConstants.DISK_TYPE_PREMIUM_MD, aemConfigResult);
                        this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM OS Disk SLA IOPS", "osdisk.sla.throughput", sapmonPublicConfig, sla.TP, aemConfigResult);
                        this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM OS Disk SLA Throughput", "osdisk.sla.iops", sapmonPublicConfig, sla.IOPS, aemConfigResult);
                    }
                    else
                    {
                        this._Helper.WriteWarning("[WARN] Standard Managed Disks are not supported.");
                    }
                }

                if (osdisk.ManagedDisk == null)
                {
                    this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM OS disk name", "osdisk.name", sapmonPublicConfig, this._Helper.GetDiskName(osdisk.Vhd.Uri), aemConfigResult);
                }


                var diskNumber = 1;
                foreach (var disk in dataDisks)
                {
                    if (disk.ManagedDisk != null)
                    {
                        var resId = new ResourceIdentifier(disk.ManagedDisk.Id);

                        var diskMD = ComputeClient.ComputeManagementClient.Disks.Get(resId.ResourceGroupName, resId.ResourceName);

                        if (diskMD.Sku.Name == StorageAccountTypes.PremiumLRS)
                        {
                            var sla = this._Helper.GetDiskSLA(diskMD.DiskSizeGB, null);

                            this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM Data Disk " + diskNumber + " Type", "disk.type." + diskNumber, sapmonPublicConfig, AEMExtensionConstants.DISK_TYPE_PREMIUM_MD, aemConfigResult);
                            this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM Data Disk " + diskNumber + " SLA IOPS", "disk.sla.throughput." + diskNumber, sapmonPublicConfig, sla.TP, aemConfigResult);
                            this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM Data Disk " + diskNumber + " SLA Throughput", "disk.sla.iops." + diskNumber, sapmonPublicConfig, sla.IOPS, aemConfigResult);
                        }
                        else if (diskMD.Sku.Name == StorageAccountTypes.UltraSSDLRS)
                        {
                            this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM Data Disk " + diskNumber + " Type", "disk.type." + diskNumber, sapmonPublicConfig, AEMExtensionConstants.DISK_TYPE_PREMIUM_MD, aemConfigResult);
                            this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM Data Disk " + diskNumber + " SLA IOPS", "disk.sla.throughput." + diskNumber, sapmonPublicConfig, diskMD.DiskMBpsReadWrite, aemConfigResult);
                            this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM Data Disk " + diskNumber + " SLA Throughput", "disk.sla.iops." + diskNumber, sapmonPublicConfig, diskMD.DiskIOPSReadWrite, aemConfigResult);
                        }
                        else
                        {
                            this._Helper.WriteWarning("[WARN] Standard Managed Disks are not supported.");
                        }
                    }
                    else
                    {
                        var accountName = this._Helper.GetStorageAccountFromUri(disk.Vhd.Uri);
                        storage = this._Helper.GetStorageAccountFromCache(accountName);
                        var accountIsPremium = this._Helper.IsPremiumStorageAccount(storage);

                        this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM Data Disk " + diskNumber + " LUN", "disk.lun." + diskNumber, sapmonPublicConfig, disk.Lun, aemConfigResult);
                        if (!accountIsPremium)
                        {
                            var endpoint  = this._Helper.GetAzureSAPTableEndpoint(storage);
                            var minuteUri = endpoint + "$MetricsMinutePrimaryTransactionsBlob";

                            this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM Data Disk " + diskNumber + " URI Key", "disk.connminute." + diskNumber, sapmonPublicConfig, accountName + ".minute", aemConfigResult);
                            this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM Data Disk " + diskNumber + " URI Value", accountName + ".minute.uri", sapmonPublicConfig, minuteUri, aemConfigResult);
                            this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM Data Disk " + diskNumber + " URI Name", accountName + ".minute.name", sapmonPublicConfig, accountName, aemConfigResult);
                            this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM Data Disk " + diskNumber + " Type", "disk.type." + diskNumber, sapmonPublicConfig, AEMExtensionConstants.DISK_TYPE_STANDARD, aemConfigResult);
                        }
                        else
                        {
                            var sla = this._Helper.GetDiskSLA(disk);

                            this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM Data Disk " + diskNumber + " Type", "disk.type." + diskNumber, sapmonPublicConfig, AEMExtensionConstants.DISK_TYPE_PREMIUM, aemConfigResult);
                            this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM Data Disk " + diskNumber + " SLA IOPS", "disk.sla.throughput." + diskNumber, sapmonPublicConfig, sla.TP, aemConfigResult);
                            this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM Data Disk " + diskNumber + " SLA Throughput", "disk.sla.iops." + diskNumber, sapmonPublicConfig, sla.IOPS, aemConfigResult);
                        }

                        this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM Data Disk " + diskNumber + " name", "disk.name." + diskNumber, sapmonPublicConfig, this._Helper.GetDiskName(disk.Vhd.Uri), aemConfigResult);
                    }

                    diskNumber += 1;
                }
                if (dataDisks.Count == 0)
                {
                    aemConfigResult.PartialResults.Add(new AEMTestResult("Azure Enhanced Monitoring Extension for SAP public configuration check: VM Data Disks", true));
                    this._Helper.WriteHost("\tAzure Enhanced Monitoring Extension for SAP public configuration check: VM Data Disks ", false);
                    this._Helper.WriteHost("OK ", ConsoleColor.Green);
                }
            }
            else
            {
                aemConfigResult.Result = false;
                this._Helper.WriteHost("NOT OK ", ConsoleColor.Red);
            }
            //#################################################
            //#################################################


            //#################################################
            //# Check WAD Configuration
            //#################################################
            int iswadEnabled;

            if (this._Helper.GetMonPropertyValue("wad.isenabled", sapmonPublicConfig, out iswadEnabled) && iswadEnabled == 1)
            {
                var wadConfigResult = new AEMTestResult("IaaSDiagnostics check");
                partialResults.Add(wadConfigResult);

                string wadPublicConfig = null;
                var    wadExtension    = AEMHelper.GetWADExtension(selectedVM, this.OSType);
                if (wadExtension != null)
                {
                    wadPublicConfig = wadExtension.Settings.ToString();
                }

                this._Helper.WriteHost("IaaSDiagnostics check...", false);
                if (wadExtension != null)
                {
                    this._Helper.WriteHost(""); //New Line
                    this._Helper.WriteHost("\tIaaSDiagnostics configuration check...", false);

                    var currentJSONConfig = JsonConvert.DeserializeObject(wadPublicConfig) as Newtonsoft.Json.Linq.JObject;
                    var base64            = currentJSONConfig["xmlCfg"] as Newtonsoft.Json.Linq.JValue;
                    System.Xml.XmlDocument currentConfig = new System.Xml.XmlDocument();
                    currentConfig.LoadXml(Encoding.UTF8.GetString(System.Convert.FromBase64String(base64.Value.ToString())));


                    if (!this._Helper.CheckWADConfiguration(currentConfig))
                    {
                        wadConfigResult.PartialResults.Add(new AEMTestResult("IaaSDiagnostics configuration check", false));
                        this._Helper.WriteHost("NOT OK ", ConsoleColor.Red);
                    }
                    else
                    {
                        wadConfigResult.PartialResults.Add(new AEMTestResult("IaaSDiagnostics configuration check", true));
                        this._Helper.WriteHost("OK ", ConsoleColor.Green);
                    }

                    this._Helper.WriteHost("\tIaaSDiagnostics performance counters check...");
                    var wadPerfCountersResult = new AEMTestResult("IaaSDiagnostics performance counters check");
                    wadConfigResult.PartialResults.Add(wadPerfCountersResult);

                    foreach (var perfCounter in AEMExtensionConstants.PerformanceCounters[this.OSType])
                    {
                        this._Helper.WriteHost("\t\tIaaSDiagnostics performance counters " + (perfCounter.counterSpecifier) + "check...", false);
                        var currentCounter = currentConfig.SelectSingleNode("/WadCfg/DiagnosticMonitorConfiguration/PerformanceCounters/PerformanceCounterConfiguration[@counterSpecifier = '" + perfCounter.counterSpecifier + "']");
                        if (currentCounter != null)
                        {
                            wadPerfCountersResult.PartialResults.Add(new AEMTestResult("IaaSDiagnostics performance counters " + (perfCounter.counterSpecifier) + "check...", true));
                            this._Helper.WriteHost("OK ", ConsoleColor.Green);
                        }
                        else
                        {
                            wadPerfCountersResult.PartialResults.Add(new AEMTestResult("IaaSDiagnostics performance counters " + (perfCounter.counterSpecifier) + "check...", false));
                            this._Helper.WriteHost("NOT OK ", ConsoleColor.Red);
                        }
                    }

                    string wadstorage;
                    if (!this._Helper.GetMonPropertyValue <string>("wad.name", sapmonPublicConfig, out wadstorage))
                    {
                        wadstorage = null;
                    }

                    this._Helper.WriteHost("\tIaaSDiagnostics data check...", false);

                    var deploymentId = String.Empty;
                    var roleName     = String.Empty;

                    var extStatuses = AEMHelper.GetAEMExtensionStatus(selectedVM, selectedVMStatus, this.OSType);
                    InstanceViewStatus aemStatus = null;
                    if (extStatuses != null && extStatuses.Statuses != null)
                    {
                        aemStatus = extStatuses.Statuses.FirstOrDefault(stat => Regex.Match(stat.Message, "deploymentId=(\\S*) roleInstance=(\\S*)").Success);
                    }

                    if (aemStatus != null)
                    {
                        var match = Regex.Match(aemStatus.Message, "deploymentId=(\\S*) roleInstance=(\\S*)");
                        deploymentId = match.Groups[1].Value;
                        roleName     = match.Groups[2].Value;
                    }
                    else
                    {
                        this._Helper.WriteWarning("DeploymentId and RoleInstanceName could not be parsed from extension status");
                    }


                    var ok = false;
                    if (!this.SkipStorageCheck.IsPresent && (!String.IsNullOrEmpty(deploymentId)) && (!String.IsNullOrEmpty(roleName)) && (!String.IsNullOrEmpty(wadstorage)))
                    {
                        if (this.OSType.Equals(AEMExtensionConstants.OSTypeLinux, StringComparison.InvariantCultureIgnoreCase))
                        {
                            ok = this._Helper.CheckDiagnosticsTable(wadstorage, deploymentId,
                                                                    selectedVM.OsProfile.ComputerName, ".", this.OSType, this.WaitTimeInMinutes);
                        }
                        else
                        {
                            string filterMinute = "Role eq '" + AEMExtensionConstants.ROLECONTENT + "' and DeploymentId eq '"
                                                  + deploymentId + "' and RoleInstance eq '" + roleName + "' and PartitionKey gt '0"
                                                  + DateTime.UtcNow.AddMinutes(AEMExtensionConstants.ContentAgeInMinutes * -1).Ticks + "'";
                            ok = this._Helper.CheckTableAndContent(wadstorage, AEMExtensionConstants.WadTableName,
                                                                   filterMinute, ".", false, this.WaitTimeInMinutes);
                        }
                    }
                    if (ok && !this.SkipStorageCheck.IsPresent)
                    {
                        wadConfigResult.PartialResults.Add(new AEMTestResult("IaaSDiagnostics data check", true));
                        this._Helper.WriteHost("OK ", ConsoleColor.Green);
                    }
                    else if (!this.SkipStorageCheck.IsPresent)
                    {
                        wadConfigResult.PartialResults.Add(new AEMTestResult("IaaSDiagnostics data check", false));
                        this._Helper.WriteHost("NOT OK ", ConsoleColor.Red);
                    }
                    else
                    {
                        this._Helper.WriteHost("Skipped ", ConsoleColor.Yellow);
                    }
                }
                else
                {
                    wadConfigResult.Result = false;
                    this._Helper.WriteHost("NOT OK ", ConsoleColor.Red);
                }
            }

            return(partialResults);
        }
コード例 #23
0
        internal static VirtualMachineExtensionInstanceView GetAEMExtensionStatus(VirtualMachine virtualMachine, VirtualMachineInstanceView vmStatus, string osType)
        {
            var aemExtension = GetAEMExtension(virtualMachine, osType);

            if (aemExtension == null)
            {
                return(null);
            }

            if (vmStatus.Extensions == null)
            {
                return(null);
            }
            return(vmStatus.Extensions.FirstOrDefault(extSt => extSt.Name.Equals(aemExtension.Name)));
        }
コード例 #24
0
        internal static VirtualMachineData DeserializeVirtualMachineData(JsonElement element)
        {
            Optional <Plan> plan = default;
            Optional <IReadOnlyList <VirtualMachineExtensionData> > resources = default;
            Optional <ResourceIdentity>  identity                                = default;
            Optional <IList <string> >   zones                                   = default;
            Optional <ExtendedLocation>  extendedLocation                        = default;
            IDictionary <string, string> tags                                    = default;
            Location                                     location                = default;
            ResourceIdentifier                           id                      = default;
            string                                       name                    = default;
            ResourceType                                 type                    = default;
            Optional <HardwareProfile>                   hardwareProfile         = default;
            Optional <StorageProfile>                    storageProfile          = default;
            Optional <AdditionalCapabilities>            additionalCapabilities  = default;
            Optional <OSProfile>                         osProfile               = default;
            Optional <NetworkProfile>                    networkProfile          = default;
            Optional <SecurityProfile>                   securityProfile         = default;
            Optional <DiagnosticsProfile>                diagnosticsProfile      = default;
            Optional <Models.SubResource>                availabilitySet         = default;
            Optional <Models.SubResource>                virtualMachineScaleSet  = default;
            Optional <Models.SubResource>                proximityPlacementGroup = default;
            Optional <VirtualMachinePriorityTypes>       priority                = default;
            Optional <VirtualMachineEvictionPolicyTypes> evictionPolicy          = default;
            Optional <BillingProfile>                    billingProfile          = default;
            Optional <Models.SubResource>                host                    = default;
            Optional <Models.SubResource>                hostGroup               = default;
            Optional <string>                            provisioningState       = default;
            Optional <VirtualMachineInstanceView>        instanceView            = default;
            Optional <string>                            licenseType             = default;
            Optional <string>                            vmId                    = default;
            Optional <string>                            extensionsTimeBudget    = default;
            Optional <int>                               platformFaultDomain     = default;
            Optional <ScheduledEventsProfile>            scheduledEventsProfile  = default;
            Optional <string>                            userData                = default;

            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("plan"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    plan = Plan.DeserializePlan(property.Value);
                    continue;
                }
                if (property.NameEquals("resources"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List <VirtualMachineExtensionData> array = new List <VirtualMachineExtensionData>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(VirtualMachineExtensionData.DeserializeVirtualMachineExtensionData(item));
                    }
                    resources = array;
                    continue;
                }
                if (property.NameEquals("identity"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    identity = JsonSerializer.Deserialize <ResourceIdentity>(property.Value.ToString());
                    continue;
                }
                if (property.NameEquals("zones"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List <string> array = new List <string>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(item.GetString());
                    }
                    zones = array;
                    continue;
                }
                if (property.NameEquals("extendedLocation"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    extendedLocation = ExtendedLocation.DeserializeExtendedLocation(property.Value);
                    continue;
                }
                if (property.NameEquals("tags"))
                {
                    Dictionary <string, string> dictionary = new Dictionary <string, string>();
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        dictionary.Add(property0.Name, property0.Value.GetString());
                    }
                    tags = dictionary;
                    continue;
                }
                if (property.NameEquals("location"))
                {
                    location = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("id"))
                {
                    id = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("type"))
                {
                    type = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("properties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        if (property0.NameEquals("hardwareProfile"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            hardwareProfile = HardwareProfile.DeserializeHardwareProfile(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("storageProfile"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            storageProfile = StorageProfile.DeserializeStorageProfile(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("additionalCapabilities"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            additionalCapabilities = AdditionalCapabilities.DeserializeAdditionalCapabilities(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("osProfile"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            osProfile = OSProfile.DeserializeOSProfile(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("networkProfile"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            networkProfile = NetworkProfile.DeserializeNetworkProfile(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("securityProfile"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            securityProfile = SecurityProfile.DeserializeSecurityProfile(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("diagnosticsProfile"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            diagnosticsProfile = DiagnosticsProfile.DeserializeDiagnosticsProfile(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("availabilitySet"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            availabilitySet = Models.SubResource.DeserializeSubResource(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("virtualMachineScaleSet"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            virtualMachineScaleSet = Models.SubResource.DeserializeSubResource(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("proximityPlacementGroup"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            proximityPlacementGroup = Models.SubResource.DeserializeSubResource(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("priority"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            priority = new VirtualMachinePriorityTypes(property0.Value.GetString());
                            continue;
                        }
                        if (property0.NameEquals("evictionPolicy"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            evictionPolicy = new VirtualMachineEvictionPolicyTypes(property0.Value.GetString());
                            continue;
                        }
                        if (property0.NameEquals("billingProfile"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            billingProfile = BillingProfile.DeserializeBillingProfile(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("host"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            host = Models.SubResource.DeserializeSubResource(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("hostGroup"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            hostGroup = Models.SubResource.DeserializeSubResource(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("provisioningState"))
                        {
                            provisioningState = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("instanceView"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            instanceView = VirtualMachineInstanceView.DeserializeVirtualMachineInstanceView(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("licenseType"))
                        {
                            licenseType = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("vmId"))
                        {
                            vmId = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("extensionsTimeBudget"))
                        {
                            extensionsTimeBudget = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("platformFaultDomain"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            platformFaultDomain = property0.Value.GetInt32();
                            continue;
                        }
                        if (property0.NameEquals("scheduledEventsProfile"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            scheduledEventsProfile = ScheduledEventsProfile.DeserializeScheduledEventsProfile(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("userData"))
                        {
                            userData = property0.Value.GetString();
                            continue;
                        }
                    }
                    continue;
                }
            }
            return(new VirtualMachineData(id, name, type, tags, location, plan.Value, Optional.ToList(resources), identity, Optional.ToList(zones), extendedLocation.Value, hardwareProfile.Value, storageProfile.Value, additionalCapabilities.Value, osProfile.Value, networkProfile.Value, securityProfile.Value, diagnosticsProfile.Value, availabilitySet.Value, virtualMachineScaleSet.Value, proximityPlacementGroup.Value, Optional.ToNullable(priority), Optional.ToNullable(evictionPolicy), billingProfile.Value, host.Value, hostGroup.Value, provisioningState.Value, instanceView.Value, licenseType.Value, vmId.Value, extensionsTimeBudget.Value, Optional.ToNullable(platformFaultDomain), scheduledEventsProfile.Value, userData.Value));
        }
コード例 #25
0
        private VirtualMachine SetAzureVMDiagnosticsExtensionC(VirtualMachine vm, VirtualMachineInstanceView vmStatus, string storageAccountName, string storageAccountKey)
        {
            System.Xml.XmlDocument xpublicConfig = null;

            var extensionName = AEMExtensionConstants.WADExtensionDefaultName[this.OSType];

            var extTemp = this._Helper.GetExtension(vm,
                                                    AEMExtensionConstants.WADExtensionType[this.OSType], AEMExtensionConstants.WADExtensionPublisher[OSType]);
            object publicConf = null;

            if (extTemp != null)
            {
                publicConf    = extTemp.Settings;
                extensionName = extTemp.Name;
            }

            if (publicConf != null)
            {
                var jpublicConf = publicConf as Newtonsoft.Json.Linq.JObject;
                if (jpublicConf == null)
                {
                    throw new ArgumentException();
                }

                var base64 = jpublicConf["xmlCfg"] as Newtonsoft.Json.Linq.JValue;
                if (base64 == null)
                {
                    throw new ArgumentException();
                }

                System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
                xDoc.LoadXml(Encoding.UTF8.GetString(System.Convert.FromBase64String(base64.Value.ToString())));

                if (xDoc.SelectSingleNode("/WadCfg/DiagnosticMonitorConfiguration/PerformanceCounters") != null)
                {
                    xDoc.SelectSingleNode("WadCfg/DiagnosticMonitorConfiguration").Attributes["overallQuotaInMB"].Value = "4096";
                    xDoc.SelectSingleNode("WadCfg/DiagnosticMonitorConfiguration/PerformanceCounters").Attributes["scheduledTransferPeriod"].Value = "PT1M";

                    xpublicConfig = xDoc;
                }
            }

            if (xpublicConfig == null)
            {
                xpublicConfig = new System.Xml.XmlDocument();
                xpublicConfig.LoadXml(AEMExtensionConstants.WADConfigXML);
            }

            foreach (var perfCounter in AEMExtensionConstants.PerformanceCounters[OSType])
            {
                var currentCounter = xpublicConfig.
                                     SelectSingleNode("WadCfg/DiagnosticMonitorConfiguration/PerformanceCounters/PerformanceCounterConfiguration[@counterSpecifier = '" + perfCounter.counterSpecifier + "']");
                if (currentCounter == null)
                {
                    var node = xpublicConfig.CreateElement("PerformanceCounterConfiguration");
                    xpublicConfig.SelectSingleNode("WadCfg/DiagnosticMonitorConfiguration/PerformanceCounters").AppendChild(node);
                    node.SetAttribute("counterSpecifier", perfCounter.counterSpecifier);
                    node.SetAttribute("sampleRate", perfCounter.sampleRate);
                }
            }

            var endpoint = this._Helper.GetCoreEndpoint(storageAccountName);

            endpoint = "https://" + endpoint;

            Newtonsoft.Json.Linq.JObject jPublicConfig = new Newtonsoft.Json.Linq.JObject();
            jPublicConfig.Add("xmlCfg", new Newtonsoft.Json.Linq.JValue(System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(xpublicConfig.InnerXml))));

            Newtonsoft.Json.Linq.JObject jPrivateConfig = new Newtonsoft.Json.Linq.JObject();
            jPrivateConfig.Add("storageAccountName", new Newtonsoft.Json.Linq.JValue(storageAccountName));
            jPrivateConfig.Add("storageAccountKey", new Newtonsoft.Json.Linq.JValue(storageAccountKey));
            jPrivateConfig.Add("storageAccountEndPoint", new Newtonsoft.Json.Linq.JValue(endpoint));

            WriteVerbose("Installing WAD extension");

            Version wadVersion = this._Helper.GetExtensionVersion(vm, vmStatus, OSType,
                                                                  AEMExtensionConstants.WADExtensionType[this.OSType], AEMExtensionConstants.WADExtensionPublisher[this.OSType]);

            VirtualMachineExtension vmExtParameters = new VirtualMachineExtension();

            vmExtParameters.Publisher = AEMExtensionConstants.WADExtensionPublisher[this.OSType];
            vmExtParameters.VirtualMachineExtensionType = AEMExtensionConstants.WADExtensionType[this.OSType];
            vmExtParameters.TypeHandlerVersion          = wadVersion.ToString(2);
            vmExtParameters.Settings                = jPublicConfig;
            vmExtParameters.ProtectedSettings       = jPrivateConfig;
            vmExtParameters.Location                = vm.Location;
            vmExtParameters.AutoUpgradeMinorVersion = true;
            vmExtParameters.ForceUpdateTag          = DateTime.Now.Ticks.ToString();

            this.VirtualMachineExtensionClient.CreateOrUpdate(ResourceGroupName, vm.Name, extensionName, vmExtParameters);

            return(this.ComputeClient.ComputeManagementClient.VirtualMachines.Get(ResourceGroupName, vm.Name));
        }
コード例 #26
0
        private List <AEMTestResult> TestNewExtension(VirtualMachine selectedVM, VirtualMachineInstanceView selectedVMStatus, VirtualMachineExtension monExtension)
        {
            List <AEMTestResult> partialResults = new List <AEMTestResult>();

            this._Helper.WriteHost("Azure Extension for SAP Installation check...", false);
            if (!AEMHelper.IsNewExtension(monExtension, this.OSType))
            {
                partialResults.Add(new AEMTestResult("Azure Extension for SAP Installation check", false));
                this._Helper.WriteHost("NOT OK ", ConsoleColor.Red);
            }
            else
            {
                partialResults.Add(new AEMTestResult("Azure Extension for SAP Installation check", true));
                this._Helper.WriteHost("OK ", ConsoleColor.Green);
            }


            this._Helper.WriteHost("VM Identity Check...", false);
            if (selectedVM.Identity == null || selectedVM.Identity.Type == ResourceIdentityType.UserAssigned)
            {
                partialResults.Add(new AEMTestResult("VM Identity Check", false));
                this._Helper.WriteHost("NOT OK ", ConsoleColor.Red);
            }
            else
            {
                partialResults.Add(new AEMTestResult("VM Identity Check", true));
                this._Helper.WriteHost("OK ", ConsoleColor.Green);
            }


            var permissionResult = new AEMTestResult("Permission Check");

            partialResults.Add(permissionResult);
            this._Helper.WriteHost("Permission Check...", true);
            List <string> resourceIds = new List <string>();

            int endIndexShort = 4; //Scope is set to resource group
            int endIndexLong  = 8; //Scope is set to resource

            // Add VM Scope or Resource Group scope
            resourceIds.Add(selectedVM.Id);

            //TODO: do we want to support unmanaged disks?
            resourceIds.Add(selectedVM.StorageProfile.OsDisk.ManagedDisk.Id);

            foreach (var dataDisk in selectedVM.StorageProfile.DataDisks)
            {
                resourceIds.Add(dataDisk.ManagedDisk.Id);
            }
            foreach (var nic in selectedVM.NetworkProfile.NetworkInterfaces)
            {
                resourceIds.Add(nic.Id);
            }

            /*
             * Individual resources could be located in different resource groups.
             * We therefore have to check both the resource group scope and the resource scope for every resource
             */
            HashSet <string> testedScopeOK  = new HashSet <string>();
            HashSet <string> testedScopeNOK = new HashSet <string>();

            foreach (string resourceId in resourceIds)
            {
                string scopeResourceGroup        = String.Join("/", resourceId.Split('/').SubArray(0, endIndexShort));
                string scopeResource             = String.Join("/", resourceId.Split('/').SubArray(0, endIndexLong));
                string scopedRoleIdResourceGroup = $"{scopeResourceGroup}/providers/Microsoft.Authorization/roleDefinitions/{AEMExtensionConstants.NewExtensionRole}";
                string scopedRoleIdResource      = $"{scopeResource}/providers/Microsoft.Authorization/roleDefinitions/{AEMExtensionConstants.NewExtensionRole}";
                string roleDefinitionId          = $"/subscriptions/{this.DefaultContext.Subscription.Id}/providers/Microsoft.Authorization/roleDefinitions/{AEMExtensionConstants.NewExtensionRole}";

                this._Helper.WriteHost("\tPermission Check for Resource {0}...", false, resourceId);
                bool checkOk = false;
                bool?groupOK = null;
                if (testedScopeOK.Contains(scopeResourceGroup))
                {
                    groupOK = true;
                }
                if (testedScopeNOK.Contains(scopeResourceGroup))
                {
                    groupOK = false;
                }
                bool?resourceOk = null;
                if (testedScopeOK.Contains(scopeResource))
                {
                    resourceOk = true;
                }
                if (testedScopeNOK.Contains(scopeResource))
                {
                    resourceOk = false;
                }

                checkOk = AEMHelper.CheckScopePermissions(groupOK, resourceOk, scopeResourceGroup, scopeResource, roleDefinitionId, selectedVM, testedScopeOK, testedScopeNOK, this.TestScope);

                if (checkOk)
                {
                    permissionResult.PartialResults.Add(new AEMTestResult("Permission Check for Resource {0}", true, resourceId));
                    this._Helper.WriteHost("OK ", ConsoleColor.Green);
                }
                else
                {
                    permissionResult.PartialResults.Add(new AEMTestResult("Permission Check for Resource {0}", false, resourceId));
                    this._Helper.WriteHost("NOT OK ", ConsoleColor.Red);
                }
            }

            return(partialResults);
        }