Exemplo n.º 1
0
        public void CanCRUDLocks()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                IAuthorizationManager authorizationManager = TestHelper.CreateAuthorizationManager();
                IComputeManager       computeManager       = TestHelper.CreateComputeManager();
                IResourceManager      managerResources     = computeManager.ResourceManager;
                INetworkManager       networkManager       = TestHelper.CreateNetworkManager();
                IStorageManager       storageManager       = TestHelper.CreateStorageManager();

                // Prepare a VM
                string password    = SdkContext.RandomResourceName("P@s", 14);
                string rgName      = SdkContext.RandomResourceName("rg", 15);
                string vmName      = SdkContext.RandomResourceName("vm", 15);
                string storageName = SdkContext.RandomResourceName("st", 15);
                string diskName    = SdkContext.RandomResourceName("dsk", 15);
                string netName     = SdkContext.RandomResourceName("net", 15);
                Region region      = Region.USEast;

                IResourceGroup  resourceGroup = null;
                IManagementLock lockGroup     = null,
                                lockVM        = null,
                                lockStorage   = null,
                                lockDiskRO    = null,
                                lockDiskDel   = null,
                                lockSubnet    = null;

                try
                {
                    resourceGroup = managerResources.ResourceGroups.Define(rgName)
                                    .WithRegion(region)
                                    .Create();
                    Assert.NotNull(resourceGroup);

                    ICreatable <INetwork> netDefinition = networkManager.Networks.Define(netName)
                                                          .WithRegion(region)
                                                          .WithExistingResourceGroup(resourceGroup)
                                                          .WithAddressSpace("10.0.0.0/28");

                    // Define a VM for testing VM locks
                    ICreatable <IVirtualMachine> vmDefinition = computeManager.VirtualMachines.Define(vmName)
                                                                .WithRegion(region)
                                                                .WithExistingResourceGroup(resourceGroup)
                                                                .WithNewPrimaryNetwork(netDefinition)
                                                                .WithPrimaryPrivateIPAddressDynamic()
                                                                .WithoutPrimaryPublicIPAddress()
                                                                .WithPopularWindowsImage(KnownWindowsVirtualMachineImage.WindowsServer2012R2Datacenter)
                                                                .WithAdminUsername("tester")
                                                                .WithAdminPassword(password)
                                                                .WithSize(VirtualMachineSizeTypes.BasicA1);

                    // Define a managed disk for testing locks on that
                    ICreatable <IDisk> diskDefinition = computeManager.Disks.Define(diskName)
                                                        .WithRegion(region)
                                                        .WithExistingResourceGroup(resourceGroup)
                                                        .WithData()
                                                        .WithSizeInGB(100);

                    // Define a storage account for testing locks on that
                    ICreatable <IStorageAccount> storageDefinition = storageManager.StorageAccounts.Define(storageName)
                                                                     .WithRegion(region)
                                                                     .WithExistingResourceGroup(resourceGroup);

                    // Create resources in parallel to save time and money
                    Extensions.Synchronize(() => Task.WhenAll(
                                               storageDefinition.CreateAsync(),
                                               vmDefinition.CreateAsync(),
                                               diskDefinition.CreateAsync()));

                    IVirtualMachine vm      = (IVirtualMachine)vmDefinition;
                    IStorageAccount storage = (IStorageAccount)storageDefinition;
                    IDisk           disk    = (IDisk)diskDefinition;
                    INetwork        network = vm.GetPrimaryNetworkInterface().PrimaryIPConfiguration.GetNetwork();
                    ISubnet         subnet  = network.Subnets.Values.FirstOrDefault();

                    // Lock subnet
                    ICreatable <IManagementLock> lockSubnetDef = authorizationManager.ManagementLocks.Define("subnetLock")
                                                                 .WithLockedResource(subnet.Inner.Id)
                                                                 .WithLevel(LockLevel.ReadOnly);

                    // Lock VM
                    ICreatable <IManagementLock> lockVMDef = authorizationManager.ManagementLocks.Define("vmlock")
                                                             .WithLockedResource(vm)
                                                             .WithLevel(LockLevel.ReadOnly)
                                                             .WithNotes("vm readonly lock");

                    // Lock resource group
                    ICreatable <IManagementLock> lockGroupDef = authorizationManager.ManagementLocks.Define("rglock")
                                                                .WithLockedResource(resourceGroup.Id)
                                                                .WithLevel(LockLevel.CanNotDelete);

                    // Lock storage
                    ICreatable <IManagementLock> lockStorageDef = authorizationManager.ManagementLocks.Define("stLock")
                                                                  .WithLockedResource(storage)
                                                                  .WithLevel(LockLevel.CanNotDelete);

                    // Create locks in parallel
                    ICreatedResources <IManagementLock> created = authorizationManager.ManagementLocks.Create(lockVMDef, lockGroupDef, lockStorageDef, lockSubnetDef);

                    lockVM      = created.FirstOrDefault(o => o.Key.Equals(lockVMDef.Key));
                    lockStorage = created.FirstOrDefault(o => o.Key.Equals(lockStorageDef.Key));
                    lockGroup   = created.FirstOrDefault(o => o.Key.Equals(lockGroupDef.Key));
                    lockSubnet  = created.FirstOrDefault(o => o.Key.Equals(lockSubnetDef.Key));

                    // Lock disk synchronously
                    lockDiskRO = authorizationManager.ManagementLocks.Define("diskLockRO")
                                 .WithLockedResource(disk)
                                 .WithLevel(LockLevel.ReadOnly)
                                 .Create();

                    lockDiskDel = authorizationManager.ManagementLocks.Define("diskLockDel")
                                  .WithLockedResource(disk)
                                  .WithLevel(LockLevel.CanNotDelete)
                                  .Create();

                    // Verify VM lock
                    Assert.Equal(2, authorizationManager.ManagementLocks.ListForResource(vm.Id).Count());

                    Assert.NotNull(lockVM);
                    lockVM = authorizationManager.ManagementLocks.GetById(lockVM.Id);
                    Assert.NotNull(lockVM);
                    Assert.Equal(LockLevel.ReadOnly, lockVM.Level);
                    Assert.Equal(vm.Id, lockVM.LockedResourceId, true);

                    // Verify resource group lock
                    Assert.NotNull(lockGroup);
                    lockGroup = authorizationManager.ManagementLocks.GetByResourceGroup(resourceGroup.Name, "rglock");
                    Assert.NotNull(lockGroup);
                    Assert.Equal(LockLevel.CanNotDelete, lockGroup.Level);
                    Assert.Equal(resourceGroup.Id, lockGroup.LockedResourceId, true);

                    // Verify storage account lock
                    Assert.Equal(2, authorizationManager.ManagementLocks.ListForResource(storage.Id).Count());

                    Assert.NotNull(lockStorage);
                    lockStorage = authorizationManager.ManagementLocks.GetById(lockStorage.Id);
                    Assert.NotNull(lockStorage);
                    Assert.Equal(LockLevel.CanNotDelete, lockStorage.Level);
                    Assert.Equal(storage.Id, lockStorage.LockedResourceId, true);

                    // Verify disk lock
                    Assert.Equal(3, authorizationManager.ManagementLocks.ListForResource(disk.Id).Count());

                    Assert.NotNull(lockDiskRO);
                    lockDiskRO = authorizationManager.ManagementLocks.GetById(lockDiskRO.Id);
                    Assert.NotNull(lockDiskRO);
                    Assert.Equal(LockLevel.ReadOnly, lockDiskRO.Level);
                    Assert.Equal(disk.Id, lockDiskRO.LockedResourceId, true);

                    Assert.NotNull(lockDiskDel);
                    lockDiskDel = authorizationManager.ManagementLocks.GetById(lockDiskDel.Id);
                    Assert.NotNull(lockDiskDel);
                    Assert.Equal(LockLevel.CanNotDelete, lockDiskDel.Level);
                    Assert.Equal(disk.Id, lockDiskDel.LockedResourceId, true);

                    // Verify subnet lock
                    Assert.Equal(2, authorizationManager.ManagementLocks.ListForResource(network.Id).Count());

                    lockSubnet = authorizationManager.ManagementLocks.GetById(lockSubnet.Id);
                    Assert.NotNull(lockSubnet);
                    Assert.Equal(LockLevel.ReadOnly, lockSubnet.Level);
                    Assert.Equal(subnet.Inner.Id, lockSubnet.LockedResourceId, true);

                    // Verify lock collection
                    var locksSubscription = authorizationManager.ManagementLocks.List();
                    var locksGroup        = authorizationManager.ManagementLocks.ListByResourceGroup(vm.ResourceGroupName);
                    Assert.NotNull(locksSubscription);
                    Assert.NotNull(locksGroup);

                    int locksAllCount = locksSubscription.Count();
                    Assert.True(6 <= locksAllCount);

                    int locksGroupCount = locksGroup.Count();
                    Assert.Equal(6, locksGroup.Count());
                }
                finally
                {
                    try
                    {
                        if (resourceGroup != null)
                        {
                            if (lockGroup != null)
                            {
                                authorizationManager.ManagementLocks.DeleteById(lockGroup.Id);
                            }
                            if (lockVM != null)
                            {
                                authorizationManager.ManagementLocks.DeleteById(lockVM.Id);
                            }
                            if (lockDiskRO != null)
                            {
                                authorizationManager.ManagementLocks.DeleteById(lockDiskRO.Id);
                            }
                            if (lockDiskDel != null)
                            {
                                authorizationManager.ManagementLocks.DeleteById(lockDiskDel.Id);
                            }
                            if (lockStorage != null)
                            {
                                authorizationManager.ManagementLocks.DeleteById(lockStorage.Id);
                            }
                            if (lockSubnet != null)
                            {
                                authorizationManager.ManagementLocks.DeleteById(lockSubnet.Id);
                            }

                            managerResources.ResourceGroups.BeginDeleteByName(rgName);
                        }
                    }
                    catch { }
                }
            }
        }
Exemplo n.º 2
0
        /**
         * Azure Network sample for managing virtual network gateway.
         *  - Create 2 virtual networks with subnets and 2 virtual network gateways corresponding to each network
         *  - Create VPN VNet-to-VNet connection
         *  - Troubleshoot the connection
         *    - Create network watcher in the same region as virtual network gateway
         *    - Create storage account to store troubleshooting information
         *    - Run troubleshooting for the connection - result will be 'UnHealthy' as need to create symmetrical connection from second gateway to the first
         *  - Create virtual network connection from second gateway to the first and run troubleshooting. Result will be 'Healthy'.
         *  - List VPN Gateway connections for the first gateway
         *  - Create 2 virtual machines, each one in its network and verify connectivity between them
         */
        public static void RunSample(IAzure azure)
        {
            string rgName          = SdkContext.RandomResourceName("rg", 24);
            string vnetName        = SdkContext.RandomResourceName("vnet", 20);
            string vnet2Name       = SdkContext.RandomResourceName("vnet", 20);
            string vpnGatewayName  = SdkContext.RandomResourceName("vngw", 20);
            string vpnGateway2Name = SdkContext.RandomResourceName("vngw2", 20);
            string connectionName  = SdkContext.RandomResourceName("con", 20);
            string connection2Name = SdkContext.RandomResourceName("con2", 20);
            string nwName          = SdkContext.RandomResourceName("nw", 20);
            string vm1Name         = SdkContext.RandomResourceName("vm1", 20);
            string vm2Name         = SdkContext.RandomResourceName("vm2", 20);
            string rootname        = Utilities.CreateUsername();
            string password        = SdkContext.RandomResourceName("pWd!", 15);
            string containerName   = "results";

            try
            {
                //============================================================
                // Create virtual network
                Utilities.Log("Creating virtual network...");
                INetwork network1 = azure.Networks.Define(vnetName)
                                    .WithRegion(region)
                                    .WithNewResourceGroup(rgName)
                                    .WithAddressSpace("10.11.0.0/16")
                                    .WithSubnet("GatewaySubnet", "10.11.255.0/27")
                                    .WithSubnet("Subnet1", "10.11.0.0/24")
                                    .Create();
                Utilities.Log("Created network");
                // Print the virtual network
                Utilities.PrintVirtualNetwork(network1);

                //============================================================
                // Create virtual network gateway
                Utilities.Log("Creating virtual network gateway...");
                IVirtualNetworkGateway vngw1 = azure.VirtualNetworkGateways.Define(vpnGatewayName)
                                               .WithRegion(region)
                                               .WithNewResourceGroup(rgName)
                                               .WithExistingNetwork(network1)
                                               .WithRouteBasedVpn()
                                               .WithSku(VirtualNetworkGatewaySkuName.VpnGw1)
                                               .Create();
                Utilities.Log("Created virtual network gateway");

                //============================================================
                // Create second virtual network
                Utilities.Log("Creating virtual network...");
                INetwork network2 = azure.Networks.Define(vnet2Name)
                                    .WithRegion(region)
                                    .WithNewResourceGroup(rgName)
                                    .WithAddressSpace("10.41.0.0/16")
                                    .WithSubnet("GatewaySubnet", "10.41.255.0/27")
                                    .WithSubnet("Subnet2", "10.41.0.0/24")
                                    .Create();
                Utilities.Log("Created virtual network");

                //============================================================
                // Create second virtual network gateway
                Utilities.Log("Creating second virtual network gateway...");
                IVirtualNetworkGateway vngw2 = azure.VirtualNetworkGateways.Define(vpnGateway2Name)
                                               .WithRegion(region)
                                               .WithNewResourceGroup(rgName)
                                               .WithExistingNetwork(network2)
                                               .WithRouteBasedVpn()
                                               .WithSku(VirtualNetworkGatewaySkuName.VpnGw1)
                                               .Create();
                Utilities.Log("Created second virtual network gateway");

                //============================================================
                // Create virtual network gateway connection
                Utilities.Log("Creating virtual network gateway connection...");
                IVirtualNetworkGatewayConnection connection = vngw1.Connections
                                                              .Define(connectionName)
                                                              .WithVNetToVNet()
                                                              .WithSecondVirtualNetworkGateway(vngw2)
                                                              .WithSharedKey("MySecretKey")
                                                              .Create();
                Utilities.Log("Created virtual network gateway connection");

                //============================================================
                // Troubleshoot the connection

                // create Network Watcher
                INetworkWatcher nw = azure.NetworkWatchers.Define(nwName)
                                     .WithRegion(region)
                                     .WithExistingResourceGroup(rgName)
                                     .Create();
                // Create storage account to store troubleshooting information
                IStorageAccount storageAccount = azure.StorageAccounts.Define("sa" + SdkContext.RandomResourceName("", 8))
                                                 .WithRegion(region)
                                                 .WithExistingResourceGroup(rgName)
                                                 .Create();
                // Create storage container to store troubleshooting results
                string accountKey       = storageAccount.GetKeys()[0].Value;
                string connectionString = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", storageAccount.Name, accountKey);
                Utilities.CreateContainer(connectionString, containerName);

                // Run troubleshooting for the connection - result will be 'UnHealthy' as need to create symmetrical connection from second gateway to the first
                ITroubleshooting troubleshooting = nw.Troubleshoot()
                                                   .WithTargetResourceId(connection.Id)
                                                   .WithStorageAccount(storageAccount.Id)
                                                   .WithStoragePath(storageAccount.EndPoints.Primary.Blob + containerName)
                                                   .Execute();
                Utilities.Log("Troubleshooting status is: " + troubleshooting.Code);

                //============================================================
                //  Create virtual network connection from second gateway to the first and run troubleshooting. Result will be 'Healthy'.
                vngw2.Connections
                .Define(connection2Name)
                .WithVNetToVNet()
                .WithSecondVirtualNetworkGateway(vngw1)
                .WithSharedKey("MySecretKey")
                .Create();
                // Delay before running troubleshooting to wait for connection settings to propagate
                SdkContext.DelayProvider.Delay(250000);
                troubleshooting = nw.Troubleshoot()
                                  .WithTargetResourceId(connection.Id)
                                  .WithStorageAccount(storageAccount.Id)
                                  .WithStoragePath(storageAccount.EndPoints.Primary.Blob + containerName)
                                  .Execute();
                Utilities.Log("Troubleshooting status is: " + troubleshooting.Code);

                //============================================================
                // List VPN Gateway connections for particular gateway
                var connections = vngw1.ListConnections();
                foreach (var conn in connections)
                {
                    Utilities.Print(conn);
                }

                //============================================================
                // Create 2 virtual machines, each one in its network and verify connectivity between them
                List <ICreatable <IVirtualMachine> > vmDefinitions = new List <ICreatable <IVirtualMachine> >();

                vmDefinitions.Add(azure.VirtualMachines.Define(vm1Name)
                                  .WithRegion(region)
                                  .WithExistingResourceGroup(rgName)
                                  .WithExistingPrimaryNetwork(network1)
                                  .WithSubnet("Subnet1")
                                  .WithPrimaryPrivateIPAddressDynamic()
                                  .WithoutPrimaryPublicIPAddress()
                                  .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
                                  .WithRootUsername(rootname)
                                  .WithRootPassword(password)
                                  // Extension currently needed for network watcher support
                                  .DefineNewExtension("networkWatcher")
                                  .WithPublisher("Microsoft.Azure.NetworkWatcher")
                                  .WithType("NetworkWatcherAgentLinux")
                                  .WithVersion("1.4")
                                  .Attach());
                vmDefinitions.Add(azure.VirtualMachines.Define(vm2Name)
                                  .WithRegion(region)
                                  .WithExistingResourceGroup(rgName)
                                  .WithExistingPrimaryNetwork(network2)
                                  .WithSubnet("Subnet2")
                                  .WithPrimaryPrivateIPAddressDynamic()
                                  .WithoutPrimaryPublicIPAddress()
                                  .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
                                  .WithRootUsername(rootname)
                                  .WithRootPassword(password)
                                  // Extension currently needed for network watcher support
                                  .DefineNewExtension("networkWatcher")
                                  .WithPublisher("Microsoft.Azure.NetworkWatcher")
                                  .WithType("NetworkWatcherAgentLinux")
                                  .WithVersion("1.4")
                                  .Attach());
                ICreatedResources <IVirtualMachine> createdVMs = azure.VirtualMachines.Create(vmDefinitions);
                IVirtualMachine vm1 = createdVMs.FirstOrDefault(vm => vm.Key == vmDefinitions[0].Key);
                IVirtualMachine vm2 = createdVMs.FirstOrDefault(vm => vm.Key == vmDefinitions[1].Key);

                IConnectivityCheck connectivity = nw.CheckConnectivity()
                                                  .ToDestinationResourceId(vm2.Id)
                                                  .ToDestinationPort(22)
                                                  .FromSourceVirtualMachine(vm1.Id)
                                                  .Execute();
                Utilities.Log("Connectivity status: " + connectivity.ConnectionStatus);
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + rgName);
                    azure.ResourceGroups.BeginDeleteByName(rgName);
                }
                catch (NullReferenceException)
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
                catch (Exception ex)
                {
                    Utilities.Log(ex);
                }
            }
        }
        public void CanWatchNetwork()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                string newName            = SdkContext.RandomResourceName("nw", 6);
                var    groupName          = SdkContext.RandomResourceName("rg", 6);
                var    resourcesGroupName = SdkContext.RandomResourceName("rg", 8);

                // Create network watcher
                var manager        = TestHelper.CreateNetworkManager();
                var computeManager = TestHelper.CreateComputeManager();

                // make sure Network Watcher is disabled in current subscription and region as only one can exist
                EnsureNetworkWatcherNotExists(manager.NetworkWatchers);

                var nw = manager.NetworkWatchers.Define(newName)
                         .WithRegion(REGION)
                         .WithNewResourceGroup(groupName)
                         .Create();

                // pre-create VMs to show topology on
                ICreatedResources <IVirtualMachine> virtualMachines = EnsureNetwork(manager, computeManager, resourcesGroupName);
                var       vm0      = virtualMachines.ElementAt(0);
                ITopology topology = nw.GetTopology(vm0.ResourceGroupName);
                Assert.Equal(11, topology.Resources.Count);
                Assert.True(topology.Resources.ContainsKey(vm0.PrimaryNetworkInterfaceId));
                Assert.Equal(4, topology.Resources[vm0.PrimaryNetworkInterfaceId].Associations.Count);

                ISecurityGroupView sgViewResult = nw.GetSecurityGroupView(virtualMachines.ElementAt(0).Id);
                Assert.Equal(1, sgViewResult.NetworkInterfaces.Count);
                Assert.Equal(virtualMachines.ElementAt(0).PrimaryNetworkInterfaceId,
                             sgViewResult.NetworkInterfaces.Keys.First());

                IFlowLogSettings flowLogSettings =
                    nw.GetFlowLogSettings(vm0.GetPrimaryNetworkInterface().NetworkSecurityGroupId);
                IStorageAccount storageAccount = EnsureStorageAccount(resourcesGroupName);
                flowLogSettings.Update()
                .WithLogging()
                .WithStorageAccount(storageAccount.Id)
                .WithRetentionPolicyDays(5)
                .WithRetentionPolicyEnabled()
                .Apply();
                Assert.True(flowLogSettings.Enabled);
                Assert.Equal(5, flowLogSettings.RetentionDays);
                Assert.Equal(storageAccount.Id, flowLogSettings.StorageId);

                INextHop nextHop = nw.NextHop().WithTargetResourceId(vm0.Id)
                                   .WithSourceIPAddress("10.0.0.4")
                                   .WithDestinationIPAddress("8.8.8.8")
                                   .Execute();
                Assert.Equal("System Route", nextHop.RouteTableId);
                Assert.Equal(NextHopType.Internet, nextHop.NextHopType);
                Assert.Null(nextHop.NextHopIpAddress);

                IVerificationIPFlow verificationIPFlow = nw.VerifyIPFlow()
                                                         .WithTargetResourceId(vm0.Id)
                                                         .WithDirection(Direction.Outbound)
                                                         .WithProtocol(Protocol.TCP)
                                                         .WithLocalIPAddress("10.0.0.4")
                                                         .WithRemoteIPAddress("8.8.8.8")
                                                         .WithLocalPort("443")
                                                         .WithRemotePort("443")
                                                         .Execute();
                Assert.Equal(Access.Allow, verificationIPFlow.Access);
                Assert.Equal("defaultSecurityRules/AllowInternetOutBound", verificationIPFlow.RuleName);

                // test packet capture
                IEnumerable <IPacketCapture> packetCaptures = nw.PacketCaptures.List();
                Assert.Empty(packetCaptures);
                IPacketCapture packetCapture = nw.PacketCaptures
                                               .Define("NewPacketCapture")
                                               .WithTarget(vm0.Id)
                                               .WithStorageAccountId(storageAccount.Id)
                                               .WithTimeLimitInSeconds(1500)
                                               .DefinePacketCaptureFilter()
                                               .WithProtocol(PcProtocol.TCP)
                                               .WithLocalIPAddresses(new List <string>()
                {
                    "127.0.0.1", "127.0.0.5"
                })
                                               .Attach()
                                               .Create();
                packetCaptures = nw.PacketCaptures.List();
                Assert.Single(packetCaptures);
                Assert.Equal("NewPacketCapture", packetCapture.Name);
                Assert.Equal(1500, packetCapture.TimeLimitInSeconds);
                Assert.Equal(PcProtocol.TCP.Value, packetCapture.Filters[0].Protocol);
                Assert.Equal("127.0.0.1;127.0.0.5", packetCapture.Filters[0].LocalIPAddress);
                //        Assert.assertEquals("Running", packetCapture.getStatus().packetCaptureStatus().toString());
                packetCapture.Stop();
                Assert.Equal("Stopped", packetCapture.GetStatus().PacketCaptureStatus.Value);
                nw.PacketCaptures.DeleteByName(packetCapture.Name);
                IConnectivityCheck connectivityCheck = nw.CheckConnectivity()
                                                       .ToDestinationResourceId(vm0.Id)
                                                       .ToDestinationPort(80)
                                                       .FromSourceVirtualMachine(virtualMachines.ElementAt(0).Id)
                                                       .Execute();
                Assert.Equal("Reachable", connectivityCheck.ConnectionStatus.ToString());

                computeManager.VirtualMachines.DeleteById(virtualMachines.ElementAt(1).Id);
                topology.Refresh();
                Assert.Equal(10, topology.Resources.Count);

                manager.ResourceManager.ResourceGroups.DeleteByName(nw.ResourceGroupName);
                manager.ResourceManager.ResourceGroups.DeleteByName(resourcesGroupName);
            }
        }
        // This test put multiple zonal virtual machine's NIC into backend pool of a zone-redundant load balancer.
        // There is a bug in the service, where such an attempt will fail with error
        // "error": {
        //    "code": "NetworkInterfaceAndLoadBalancerAreInDifferentAvailabilitySets",
        //    "message": "Network interface /subscriptions/<sub-id>/resourceGroups/<rg-name>/providers/Microsoft.Network/networkInterfaces/<nic-name> uses load balancer /subscriptions/<sub-id>/resourceGroups/<rg-name>/providers/Microsoft.Compute/virtualMachines/<vm-name>).",
        //    "details": []
        // }
        // Enable this test once it is fixed.
        //
        public void CanCreateZonedVMsAndAssociateThemWithSingleBackendPoolOfZoneResilientLB()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                string rgName = TestUtilities.GenerateName("rgzoned");
                try
                {
                    var    region      = Region.USEast2;
                    string networkName = TestUtilities.GenerateName("net");

                    var azure   = TestHelper.CreateRollupClient();
                    var network = azure.Networks.Define(networkName)
                                  .WithRegion(region)
                                  .WithNewResourceGroup(rgName)
                                  .WithAddressSpace("10.0.0.0/28")
                                  .WithSubnet("subnet1", "10.0.0.0/29")
                                  .WithSubnet("subnet2", "10.0.0.8/29")
                                  .Create();

                    string pipDnsLabel = TestUtilities.GenerateName("pip");

                    var subnets = network.Subnets.Values.GetEnumerator();
                    // Define first regional virtual machine
                    //
                    subnets.MoveNext();
                    var creatableVM1 = azure.VirtualMachines
                                       .Define(TestUtilities.GenerateName("vm1"))
                                       .WithRegion(region)
                                       .WithExistingResourceGroup(rgName)
                                       .WithExistingPrimaryNetwork(network)
                                       .WithSubnet(subnets.Current.Name) // Put VM in first subnet
                                       .WithPrimaryPrivateIPAddressDynamic()
                                       .WithoutPrimaryPublicIPAddress()
                                       .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
                                       .WithRootUsername("Foo12")
                                       .WithRootPassword("abc!@#F0orL")
                                       // Optionals
                                       .WithAvailabilityZone(AvailabilityZoneId.Zone_1)
                                       .WithSize(VirtualMachineSizeTypes.StandardD3V2);

                    subnets.MoveNext();
                    var creatableVM2 = azure.VirtualMachines
                                       .Define(TestUtilities.GenerateName("vm2"))
                                       .WithRegion(region)
                                       .WithExistingResourceGroup(rgName)
                                       .WithExistingPrimaryNetwork(network)
                                       .WithSubnet(subnets.Current.Name) // Put VM in second subnet
                                       .WithPrimaryPrivateIPAddressDynamic()
                                       .WithoutPrimaryPublicIPAddress()
                                       .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
                                       .WithRootUsername("Foo12")
                                       .WithRootPassword("abc!@#F0orL")
                                       // Optionals
                                       .WithAvailabilityZone(AvailabilityZoneId.Zone_1)
                                       .WithSize(VirtualMachineSizeTypes.StandardD3V2);

                    ICreatedResources <IVirtualMachine> createdVMs = azure.VirtualMachines.Create(creatableVM1, creatableVM2);

                    var itr = createdVMs.GetEnumerator();
                    itr.MoveNext();
                    IVirtualMachine firstVirtualMachine = itr.Current;
                    itr.MoveNext();
                    IVirtualMachine secondVirtualMachine = itr.Current;

                    var publicIPAddress = azure.PublicIPAddresses
                                          .Define(pipDnsLabel)
                                          .WithRegion(region)
                                          .WithExistingResourceGroup(rgName)
                                          .WithStaticIP()
                                                                             // Optionals
                                          .WithSku(PublicIPSkuType.Standard) //  STANDARD LB requires STANDARD PIP
                                                                             // Create PIP
                                          .Create();

                    // Creates a Internet-Facing LoadBalancer with one front-end IP configuration and
                    // two backend pool associated with this IP Config
                    //
                    var           lbName = TestUtilities.GenerateName("lb");
                    ILoadBalancer lb     = azure.LoadBalancers
                                           .Define(lbName)
                                           .WithRegion(region)
                                           .WithExistingResourceGroup(rgName)
                                           .DefineLoadBalancingRule("rule-1")
                                           .WithProtocol(TransportProtocol.Tcp)
                                           .FromFrontend("front-end-1")
                                           .FromFrontendPort(80)
                                           .ToExistingVirtualMachines(firstVirtualMachine, secondVirtualMachine)
                                           .WithProbe("tcpProbe-1")
                                           .Attach()
                                           .DefinePublicFrontend("front-end-1") // Define the frontend IP configuration used by the LB rule
                                           .WithExistingPublicIPAddress(publicIPAddress)
                                           .Attach()
                                           .DefineTcpProbe("tcpProbe-1") // Define the Probe used by the LB rule
                                           .WithPort(25)
                                           .WithIntervalInSeconds(15)
                                           .WithNumberOfProbes(5)
                                           .Attach()
                                           .WithSku(LoadBalancerSkuType.Standard) // "zone-resilient LB" which don't have the constraint that all VMs needs to be in the same availability set
                                           .Create();

                    // Zone resilient LB does not care VMs are zoned or regional, in the above cases VMs are regional.
                    //
                    // rx.Completable.merge(firstVirtualMachine.startAsync(), secondVirtualMachine.startAsync()).await();

                    // Verify frontends
                    Assert.Equal(1, lb.Frontends.Count);
                    Assert.Equal(1, lb.PublicFrontends.Count);
                    Assert.Equal(0, lb.PrivateFrontends.Count);
                    ILoadBalancerFrontend frontend = lb.Frontends.Values.First();
                    Assert.True(frontend.IsPublic);
                    ILoadBalancerPublicFrontend publicFrontend = (ILoadBalancerPublicFrontend)frontend;
                    Assert.Equal(publicIPAddress.Id, publicFrontend.PublicIPAddressId, ignoreCase: true);

                    // Verify backends
                    Assert.Equal(1, lb.Backends.Count);

                    // Verify probes
                    Assert.Equal(1, lb.TcpProbes.Count);
                    Assert.True(lb.TcpProbes.ContainsKey("tcpProbe-1"));

                    // Verify rules
                    Assert.Equal(1, lb.LoadBalancingRules.Count);
                    Assert.True(lb.LoadBalancingRules.ContainsKey("rule-1"));
                    ILoadBalancingRule rule = lb.LoadBalancingRules["rule-1"];
                    Assert.NotNull(rule.Backend);
                    Assert.Equal("tcpProbe-1", rule.Probe.Name, ignoreCase: true);
                    // Zone resilient LB does not care VMs are zoned or regional, in the above cases VMs are zoned.
                    //

                    // Note that above configuration is not possible for BASIC LB, BASIC LB has following limitation
                    // It supports VMs only in a single availability Set in a backend pool, though multiple backend pool
                    // can be associated with VMs in the single availability set, you cannot create a set of VMs in another
                    // availability set and put it in a different backend pool.
                }
                finally
                {
                    try
                    {
                        var resourceManager = TestHelper.CreateResourceManager();
                        resourceManager.ResourceGroups.DeleteByName(rgName);
                    }
                    catch { }
                }
            }
        }
        public void CreateBatchOfNetworkInterfaces()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                var testId = TestUtilities.GenerateName("");

                var azure  = TestHelper.CreateRollupClient();
                var region = Region.USEast;

                ICreatable <IResourceGroup> rgCreatable = azure.ResourceGroups
                                                          .Define("rg" + testId)
                                                          .WithRegion(region);

                string vnetName = "vnet1212";
                ICreatable <INetwork> networkCreatable = azure.Networks
                                                         .Define(vnetName)
                                                         .WithRegion(region)
                                                         .WithNewResourceGroup(rgCreatable)
                                                         .WithAddressSpace("10.0.0.0/28");

                string nic1Name = "nic1";
                ICreatable <INetworkInterface> nic1Creatable = azure.NetworkInterfaces
                                                               .Define(nic1Name)
                                                               .WithRegion(region)
                                                               .WithNewResourceGroup(rgCreatable)
                                                               .WithNewPrimaryNetwork(networkCreatable)
                                                               .WithPrimaryPrivateIPAddressStatic("10.0.0.5");

                string nic2Name = "nic2";
                ICreatable <INetworkInterface> nic2Creatable = azure.NetworkInterfaces
                                                               .Define(nic2Name)
                                                               .WithRegion(region)
                                                               .WithNewResourceGroup(rgCreatable)
                                                               .WithNewPrimaryNetwork(networkCreatable)
                                                               .WithPrimaryPrivateIPAddressStatic("10.0.0.6");

                string nic3Name = "nic3";
                ICreatable <INetworkInterface> nic3Creatable = azure.NetworkInterfaces
                                                               .Define(nic3Name)
                                                               .WithRegion(region)
                                                               .WithNewResourceGroup(rgCreatable)
                                                               .WithNewPrimaryNetwork(networkCreatable)
                                                               .WithPrimaryPrivateIPAddressStatic("10.0.0.7");

                string nic4Name = "nic4";
                ICreatable <INetworkInterface> nic4Creatable = azure.NetworkInterfaces
                                                               .Define(nic4Name)
                                                               .WithRegion(region)
                                                               .WithNewResourceGroup(rgCreatable)
                                                               .WithNewPrimaryNetwork(networkCreatable)
                                                               .WithPrimaryPrivateIPAddressStatic("10.0.0.8");

                ICreatedResources <INetworkInterface> batchNics = azure.NetworkInterfaces
                                                                  .Create(nic1Creatable, nic2Creatable, nic3Creatable, nic4Creatable);

                Assert.True(batchNics.Count() == 4);
                Assert.Contains(batchNics, nic => nic.Name.Equals(nic1Name, StringComparison.OrdinalIgnoreCase));
                Assert.Contains(batchNics, nic => nic.Name.Equals(nic2Name, StringComparison.OrdinalIgnoreCase));
                Assert.Contains(batchNics, nic => nic.Name.Equals(nic3Name, StringComparison.OrdinalIgnoreCase));
                Assert.Contains(batchNics, nic => nic.Name.Equals(nic4Name, StringComparison.OrdinalIgnoreCase));

                IResourceGroup resourceGroup = (IResourceGroup)batchNics.CreatedRelatedResource(rgCreatable.Key);
                Assert.NotNull(resourceGroup);
                INetwork network = (INetwork)batchNics.CreatedRelatedResource(networkCreatable.Key);
                Assert.NotNull(network);
                azure.ResourceGroups.DeleteByName(resourceGroup.Name);
            }
        }