Exemplo n.º 1
0
 internal void Removed(ISubnet aSubnet)
 {
     /* Do nothing on subnet removal
      *  - probably better to present users with a list of all the subnets they have had around since turning on
      *  - definitely better on closing down - all subnets are removed but we don't want the combobox to end up setting our configured subnet to 0 in the process
      */
     /*
      * int index = 0;
      *
      * foreach (Subnet subnet in iList)
      * {
      *  if (subnet.MapsTo(aSubnet))
      *  {
      *      iList.Remove(subnet);
      *
      *      if (CollectionChanged != null)
      *      {
      *          CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, subnet, index));
      *      }
      *
      *      if (CountChanged != null)
      *      {
      *          CountChanged(this, EventArgs.Empty);
      *      }
      *
      *      return;
      *  }
      *
      *  index++;
      * }
      */
 }
        // Internal utility funtion
        internal static ISubnet GetAssociatedSubnet(this INetworkManager manager, SubResource subnetRef)
        {
            if (subnetRef == null)
            {
                return(null);
            }

            // TODO: Missing ResourceUtils.ParentResourceIdFromResourceId(subnetRef.Id);
            // Replace 'ParentResourcePathFromResourceId' with 'ParentResourceIdFromResourceId'
            var vnetId     = ResourceUtils.ParentResourcePathFromResourceId(subnetRef.Id);
            var subnetName = ResourceUtils.NameFromResourceId(subnetRef.Id);

            if (vnetId == null || subnetName == null)
            {
                return(null);
            }

            var network = manager.Networks.GetById(vnetId);

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

            ISubnet value = null;

            network.Subnets.TryGetValue(subnetName, out value);
            return(value);
        }
Exemplo n.º 3
0
        public static InstanceProps InstanceProps(IVpc vpc, ISubnet subnet, IRole role, ISecurityGroup securityGroup, IvrInstanceProps props, string privateIpAddress = null)
        {
            var instanceProps = new InstanceProps
            {
                Vpc        = vpc,
                VpcSubnets = new SubnetSelection
                {
                    //SubnetType = SubnetType.PUBLIC,
                    //SubnetGroupName = subnetGroupName,
                    Subnets = new ISubnet[] { subnet },
                },
                InstanceType = InstanceType.Of(props.InstanceClass, props.InstanceSize),
                MachineImage = new WindowsImage(props.WindowsVersion),
                BlockDevices = new BlockDevice[] {
                    new BlockDevice {
                        DeviceName = "/dev/sda1",
                        Volume     = BlockDeviceVolume.Ebs(props.VolumeSize, new EbsDeviceOptions {
                            VolumeType = props.VolumeType,
                            Encrypted  = true,
                        }),
                    },
                },
                Role          = role,
                SecurityGroup = securityGroup,
            };

            if (!string.IsNullOrWhiteSpace(privateIpAddress))
            {
                instanceProps.PrivateIpAddress = privateIpAddress;
            }
            return(instanceProps);
        }
Exemplo n.º 4
0
 public Subnet(VirtualNetwork parentVirtualNetwork, ISubnet sourceSubnet, TargetSettings targetSettings)
 {
     this._ParentVirtualNetwork = parentVirtualNetwork;
     this._SourceSubnet         = sourceSubnet;
     this.SetTargetName(sourceSubnet.Name, targetSettings);
     this.AddressPrefix = sourceSubnet.AddressPrefix;
 }
Exemplo n.º 5
0
 public Subnet(MigrationTarget.VirtualNetwork parentVirtualNetwork, ISubnet sourceSubnet)
 {
     this._ParentVirtualNetwork = parentVirtualNetwork;
     this._SourceSubnet         = sourceSubnet;
     this.TargetName            = sourceSubnet.Name;
     this.AddressPrefix         = sourceSubnet.AddressPrefix;
 }
Exemplo n.º 6
0
 public Subnet(VirtualNetwork parentVirtualNetwork, ISubnet sourceSubnet, TargetSettings targetSettings, ILogProvider logProvider) : base(String.Empty, String.Empty, logProvider)
 {
     this._ParentVirtualNetwork = parentVirtualNetwork;
     this._SourceSubnet         = sourceSubnet;
     this.SetTargetName(sourceSubnet.Name, targetSettings);
     this.AddressPrefix = sourceSubnet.AddressPrefix;
 }
Exemplo n.º 7
0
        internal Subnet(ISubnet aSubnet)
        {
            iSubnet = aSubnet;

            IPAddress address = new IPAddress(iSubnet.Address);

            iDescription = address + " (" + iSubnet.AdapterName + ")";
        }
Exemplo n.º 8
0
 public Network(string region, string group, string name, NetworkConfig networkConfig, ISubnet subnet)
 {
     _networkConfig = networkConfig;
     _region        = region;
     _group         = group;
     _name          = name;
     _subnet        = subnet;
 }
Exemplo n.º 9
0
        internal Subnet(ISubnet aSubnet)
        {
            iSubnet = aSubnet;

            IPAddress address = new IPAddress(iSubnet.Address);

            iDescription = address + " (" + iSubnet.AdapterName + ")";
        }
Exemplo n.º 10
0
        public void CreateAgentVmsCore(INetwork vNet = null, ISubnet subnet = null)
        {
            var sw = new Stopwatch();

            sw.Start();

            var resourceGroup = CreateResourceGroup(GroupName);
            var avSet         = CreateAvailabilitySet(AVSet, Location, GroupName);

            if (vNet == null)
            {
                vNet = CreateVirtualNetwork(VNet, Location, GroupName, SubNet);
            }

            List <ICreatable <IVirtualMachine> > creatableVirtualMachines = new List <ICreatable <IVirtualMachine> >();

            var publicIpTasks = new List <Task <IPublicIPAddress> >();

            for (var i = 0; i < _agentConfig.SlaveVmCount; i++)
            {
                publicIpTasks.Add(CreatePublicIpAsync(PublicIpBase, Location, GroupName, PublicDnsBase, i));
            }
            var publicIps = Task.WhenAll(publicIpTasks).GetAwaiter().GetResult();

            var nsgTasks = new List <Task <INetworkSecurityGroup> >();

            for (var i = 0; i < _agentConfig.SlaveVmCount; i++)
            {
                nsgTasks.Add(CreateNetworkSecurityGroupAsync(NsgBase, Location, GroupName, _agentConfig.SshPort, i));
            }
            var nsgs = Task.WhenAll(nsgTasks).GetAwaiter().GetResult();

            var nicTasks = new List <Task <INetworkInterface> >();

            for (var i = 0; i < _agentConfig.SlaveVmCount; i++)
            {
                nicTasks.Add(CreateNetworkInterfaceAsync(NicBase, Location, GroupName, subnet == null? SubNet : subnet.Name, vNet, publicIps[i], nsgs[i], i));
            }
            var nics = Task.WhenAll(nicTasks).GetAwaiter().GetResult();

            var vmTasks = new List <Task <IWithCreate> >();

            for (var i = 0; i < _agentConfig.SlaveVmCount; i++)
            {
                vmTasks.Add(GenerateVmTemplateAsync(VmNameBase, Location, GroupName, _agentConfig.ImageId, _agentConfig.User, _agentConfig.Password, _agentConfig.Ssh, SlaveVmSize, nics[i], avSet, i));
            }

            var vms = Task.WhenAll(vmTasks).GetAwaiter().GetResult();

            creatableVirtualMachines.AddRange(vms);

            Console.WriteLine($"creating vms");
            var virtualMachines = _azure.VirtualMachines.Create(creatableVirtualMachines.ToArray());

            sw.Stop();
            Util.Log($"create vm time: {sw.Elapsed.TotalMinutes} min");
        }
Exemplo n.º 11
0
 public TimerProxy(ILogTracer logTracer, IProxyOperations proxies, IScalesetOperations scalesets, INsgOperations nsg, ICreds creds, IConfigOperations configOperations, ISubnet subnet)
 {
     _logger             = logTracer;
     _proxYOperations    = proxies;
     _scalesetOperations = scalesets;
     _nsg              = nsg;
     _creds            = creds;
     _configOperations = configOperations;
     _subnet           = subnet;
 }
Exemplo n.º 12
0
 internal void Changed(ISubnet aSubnet)
 {
     foreach (Subnet subnet in iList)
     {
         if (subnet.MapsTo(aSubnet))
         {
             subnet.Changed();
             return;
         }
     }
 }
Exemplo n.º 13
0
        public void CreateServiceVmsCore(int count = 1, INetwork vnet = null, ISubnet subnet = null)
        {
            var tasks = new List <Task>();

            for (int i = 0; i < count; i++)
            {
                var ind = i;
                tasks.Add(Task.Run(() => CreateServiceVmCore(ind, vnet, subnet)));
            }
            Task.WhenAll(tasks).Wait();
        }
Exemplo n.º 14
0
 void ISubnetHandler.SubnetChanged(ISubnet aSubnet)
 {
     // this function runs in an ohSongcast thread
     lock (iLock)
     {
         if (iSubnetList.Contains(aSubnet))
         {
             // notify in the main thread
             iInvoker.BeginInvoke(new Action(NotifySubnetListChanged));
         }
     }
 }
        public void CanCreateSiteToSiteConnection()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                string vpnGatewayName   = SdkContext.RandomResourceName("vngw", 10);
                string localGatewayName = SdkContext.RandomResourceName("lngw", 10);
                var    groupName        = SdkContext.RandomResourceName("rg", 6);
                var    manager          = TestHelper.CreateNetworkManager();
                var    connectionName   = "myNewConnection";

                // Create virtual network gateway
                IVirtualNetworkGateway vngw = manager.VirtualNetworkGateways.Define(vpnGatewayName)
                                              .WithRegion(REGION)
                                              .WithNewResourceGroup(groupName)
                                              .WithNewNetwork("10.0.0.0/25", "10.0.0.0/27")
                                              .WithRouteBasedVpn()
                                              .WithSku(VirtualNetworkGatewaySkuName.VpnGw1)
                                              .Create();
                var lngw = manager.LocalNetworkGateways.Define(localGatewayName)
                           .WithRegion(vngw.Region)
                           .WithExistingResourceGroup(vngw.ResourceGroupName)
                           .WithIPAddress("40.71.184.214")
                           .WithAddressSpace("192.168.3.0/24")
                           .Create();
                vngw.Connections
                .Define(connectionName)
                .WithSiteToSite()
                .WithLocalNetworkGateway(lngw)
                .WithSharedKey("MySecretKey")
                .Create();

                Assert.Single(vngw.IPConfigurations);
                ISubnet subnet = vngw.IPConfigurations.First().GetSubnet();
                Assert.Equal("10.0.0.0/27", subnet.AddressPrefix);

                Assert.Equal("40.71.184.214", lngw.IPAddress);
                Assert.Single(lngw.AddressSpaces);
                Assert.Equal("192.168.3.0/24", lngw.AddressSpaces.First());

                var connections = vngw.ListConnections();
                Assert.Single(connections);
                Assert.Equal(vngw.Id, connections.First().VirtualNetworkGateway1Id);
                Assert.Equal(lngw.Id, connections.First().LocalNetworkGateway2Id);

                vngw.Connections.DeleteByName(connectionName);
                connections = vngw.ListConnections();
                Assert.Empty(connections);
                manager.ResourceManager.ResourceGroups.BeginDeleteByName(groupName);
            }
        }
Exemplo n.º 16
0
        internal void Added(ISubnet aSubnet)
        {
            Subnet subnet = new Subnet(aSubnet);

            iList.Add(subnet);

            if (CollectionChanged != null)
            {
                CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, subnet));
            }

            if (CountChanged != null)
            {
                CountChanged(this, EventArgs.Empty);
            }
        }
Exemplo n.º 17
0
        public void CreateServiceVmCore(int i = 0, INetwork vnet = null, ISubnet subnet = null)
        {
            var sw = new Stopwatch();

            sw.Start();
            var resourceGroup = CreateResourceGroup(GroupName);

            if (vnet == null)
            {
                vnet = CreateVirtualNetwork(AppSvrVnet, Location, GroupName, SubNet);
            }
            var publicIp = CreatePublicIpAsync(ServicePublicIpBase, Location, GroupName, ServicePublicDnsBase, i).GetAwaiter().GetResult();
            var nsg      = CreateNetworkSecurityGroupAsync(ServiceNsgBase, Location, GroupName, _agentConfig.SshPort, i).GetAwaiter().GetResult();
            var nic      = CreateNetworkInterfaceAsync(ServiceNicBase, Location, GroupName, subnet == null? SubNet : subnet.Name, vnet, publicIp, nsg, i).GetAwaiter().GetResult();
            var vmTemp   = GenerateVmTemplateAsync(ServiceVmNameBase, Location, GroupName, _agentConfig.ImageId, _agentConfig.User, _agentConfig.Password, _agentConfig.Ssh, ServiceVmSize, nic, null, i).GetAwaiter().GetResult();

            vmTemp.Create();
            sw.Stop();
            Util.Log($"create vm time: {sw.Elapsed.TotalMinutes} min");
        }
Exemplo n.º 18
0
        public Subnet(AzureContext azureContext, MigrationTarget.VirtualNetwork parentVirtualNetwork, ISubnet source, List <NetworkSecurityGroup> networkSecurityGroups)
        {
            _AzureContext         = azureContext;
            _ParentVirtualNetwork = parentVirtualNetwork;
            _SourceSubnet         = source;

            if (source.GetType() == typeof(Asm.Subnet))
            {
                Asm.Subnet asmSubnet = (Asm.Subnet)source;

                if (asmSubnet.NetworkSecurityGroup != null)
                {
                    this.NetworkSecurityGroup = SeekNetworkSecurityGroup(networkSecurityGroups, asmSubnet.NetworkSecurityGroup.ToString());
                }

                if (asmSubnet.RouteTable != null)
                {
                    this.RouteTable = new RouteTable(azureContext, asmSubnet.RouteTable);
                }

                this.AddressPrefix = asmSubnet.AddressPrefix;
            }
            else if (source.GetType() == typeof(Arm.Subnet))
            {
                Arm.Subnet armSubnet = (Arm.Subnet)source;

                if (armSubnet.NetworkSecurityGroup != null)
                {
                    this.NetworkSecurityGroup = SeekNetworkSecurityGroup(networkSecurityGroups, armSubnet.NetworkSecurityGroup.ToString());
                }

                if (armSubnet.RouteTable != null)
                {
                    this.RouteTable = new RouteTable(azureContext, armSubnet.RouteTable);
                }

                this.AddressPrefix = armSubnet.AddressPrefix;
            }

            this.TargetName = source.Name;
        }
Exemplo n.º 19
0
        private static void CreateNodeGroup(string id, Cluster cluster, string nodeGroupName, string instanceType,
                                            ISubnet subnet, AZ az, int actualMinSize = 1, int actualMaxSize = 5)
        {
            var nodegroup = cluster.AddNodegroupCapacity($"{id}-{az}", new NodegroupProps()
            {
                NodegroupName = $"{cluster.ClusterName}-{nodeGroupName}-{az}",
                InstanceType  = new InstanceType(instanceType),
                MinSize       = actualMinSize,
                MaxSize       = actualMaxSize,
                Subnets       = new SubnetSelection {
                    Subnets = new[] { subnet }
                },
                Tags = new Dictionary <string, string>
                {
                    { "k8s.io/cluster-autoscaler/enabled", "" },
                    { "k8s.io/cluster-autoscaler/yoda", "" }
                }
            });

            nodegroup.Role.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName("CloudWatchAgentServerPolicy"));
            nodegroup.Role.AddToPrincipalPolicy(autoScalePolicy);
        }
Exemplo n.º 20
0
        public Subnet(MigrationTarget.VirtualNetwork parentVirtualNetwork, ISubnet source, List <NetworkSecurityGroup> networkSecurityGroups, List <RouteTable> routeTables, TargetSettings targetSettings, ILogProvider logProvider) : base(String.Empty, String.Empty, logProvider)
        {
            _ParentVirtualNetwork = parentVirtualNetwork;
            _SourceSubnet         = source;

            if (source.GetType() == typeof(Asm.Subnet))
            {
                Asm.Subnet asmSubnet = (Asm.Subnet)source;

                if (asmSubnet.NetworkSecurityGroup != null)
                {
                    this.NetworkSecurityGroup = SeekNetworkSecurityGroup(networkSecurityGroups, asmSubnet.NetworkSecurityGroup.ToString());
                }

                if (asmSubnet.RouteTable != null)
                {
                    this.RouteTable = SeekRouteTable(routeTables, asmSubnet.RouteTable.ToString());
                }
            }
            else if (source.GetType() == typeof(Arm.Subnet))
            {
                Arm.Subnet armSubnet = (Arm.Subnet)source;

                if (armSubnet.NetworkSecurityGroup != null)
                {
                    this.NetworkSecurityGroup = SeekNetworkSecurityGroup(networkSecurityGroups, armSubnet.NetworkSecurityGroup.ToString());
                }

                if (armSubnet.RouteTable != null)
                {
                    this.RouteTable = SeekRouteTable(routeTables, armSubnet.RouteTable.ToString());
                }
            }

            this.AddressPrefix = source.AddressPrefix;
            this.SetTargetName(source.Name, targetSettings);
        }
        public void CanCreateWithNetworking()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                var GroupName       = TestUtilities.GenerateName("rgfluentchash-");
                var NsgName         = TestUtilities.GenerateName("nsg");
                var NetworkName     = TestUtilities.GenerateName("net");
                var VMName          = TestUtilities.GenerateName("vm");
                var computeManager  = TestHelper.CreateComputeManager();
                var resourceManager = TestHelper.CreateResourceManager();
                var networkManager  = TestHelper.CreateNetworkManager();

                try
                {
                    var nsg = networkManager.NetworkSecurityGroups.Define(NsgName)
                              .WithRegion(Location)
                              .WithNewResourceGroup(GroupName)
                              .DefineRule("rule1")
                              .AllowInbound()
                              .FromAnyAddress()
                              .FromPort(80)
                              .ToAnyAddress()
                              .ToPort(80)
                              .WithProtocol(SecurityRuleProtocol.Tcp)
                              .Attach()
                              .Create();

                    ICreatable <INetwork> networkDefinition = networkManager.Networks.Define(NetworkName)
                                                              .WithRegion(Location)
                                                              .WithExistingResourceGroup(GroupName)
                                                              .WithAddressSpace("10.0.0.0/28")
                                                              .DefineSubnet("subnet1")
                                                              .WithAddressPrefix("10.0.0.0/29")
                                                              .WithExistingNetworkSecurityGroup(nsg)
                                                              .Attach();

                    // Create
                    IVirtualMachine vm = computeManager.VirtualMachines.Define(VMName)
                                         .WithRegion(Location)
                                         .WithExistingResourceGroup(GroupName)
                                         .WithNewPrimaryNetwork(networkDefinition)
                                         .WithPrimaryPrivateIPAddressDynamic()
                                         .WithoutPrimaryPublicIPAddress()
                                         .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
                                         .WithRootUsername("Foo12")
                                         .WithRootPassword("abc!@#F0orL")
                                         .Create();

                    var primaryNic = vm.GetPrimaryNetworkInterface();
                    Assert.NotNull(primaryNic);
                    var primaryIpConfig = primaryNic.PrimaryIPConfiguration;
                    Assert.NotNull(primaryIpConfig);

                    // Fetch the NSG the way before v1.2
                    Assert.NotNull(primaryIpConfig.NetworkId);
                    var network = primaryIpConfig.GetNetwork();
                    Assert.NotNull(primaryIpConfig.SubnetName);
                    ISubnet subnet = null;
                    network.Subnets.TryGetValue(primaryIpConfig.SubnetName, out subnet);
                    Assert.NotNull(subnet);
                    nsg = subnet.GetNetworkSecurityGroup();
                    Assert.NotNull(nsg);
                    Assert.Equal(NsgName, nsg.Name);
                    Assert.Equal(1, nsg.SecurityRules.Count);

                    // Fetch the NSG the v1.2 way
                    nsg = primaryIpConfig.GetNetworkSecurityGroup();
                    Assert.Equal(NsgName, nsg.Name);
                }
                finally
                {
                    try
                    {
                        resourceManager.ResourceGroups.BeginDeleteByName(GroupName);
                    }
                    catch { }
                }
            }
        }
Exemplo n.º 22
0
        public static async Async.Task <Network> Create(string region, ICreds creds, IConfigOperations configOperations, ISubnet subnet)
        {
            var group          = creds.GetBaseResourceGroup();
            var instanceConfig = await configOperations.Fetch();

            var networkConfig = instanceConfig.NetworkConfig;

            // Network names will be calculated from the address_space/subnet
            // *except* if they are the original values.  This allows backwards
            // compatibility to existing configs if you don't change the network
            // configs.

            string name;

            if (networkConfig.AddressSpace == NetworkConfig.Default.AddressSpace && networkConfig.Subnet == NetworkConfig.Default.Subnet)
            {
                name = region;
            }
            else
            {
                var networkId = Faithlife.Utility.GuidUtility.Create(NETWORK_GUID_NAMESPACE, string.Join("|", networkConfig.AddressSpace, networkConfig.Subnet), 5);
                name = $"{region}-{networkId}";
            }


            return(new Network(region, group, name, networkConfig, subnet));
        }
Exemplo n.º 23
0
 public void SubnetRemoved(ISubnet aSubnet)
 {
     iDispatcher.BeginInvoke(new DelegateSubnetList(Removed), new object[] { aSubnet });
 }
 ///GENMHASH:9324AD10F20137C7B4A5F3C5B476CA6A:6BA1DB83FAA1442223CC13159CA8F7A7
 internal LoadBalancerInboundNatPoolImpl FromExistingSubnet(ISubnet subnet)
 {
     return((null != subnet)
         ? FromExistingSubnet(subnet.Parent.Id, subnet.Name)
         : this);
 }
Exemplo n.º 25
0
        internal void Added(ISubnet aSubnet)
        {
            Subnet subnet = new Subnet(aSubnet);

            iList.Add(subnet);

            if (CollectionChanged != null)
            {
                CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, subnet));
            }

            if (CountChanged != null)
            {
                CountChanged(this, EventArgs.Empty);
            }
        }
Exemplo n.º 26
0
        public void CreateUpdateSubnetServiceAccess()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                var    testId    = TestUtilities.GenerateName("");
                string nwName    = "net" + testId;
                var    region    = Region.USWest;
                var    groupName = "rg" + testId;

                var manager = TestHelper.CreateNetworkManager();

                try
                {
                    // Create a network
                    INetwork network = manager.Networks.Define(nwName)
                                       .WithRegion(region)
                                       .WithNewResourceGroup(groupName)
                                       .WithAddressSpace("10.0.0.0/28")
                                       .WithSubnet("subnetA", "10.0.0.0/29")
                                       .DefineSubnet("subnetB")
                                       .WithAddressPrefix("10.0.0.8/29")
                                       .WithAccessFromService(ServiceEndpointType.MicrosoftStorage)
                                       .Attach()
                                       .Create();

                    // Verify address spaces
                    Assert.Single(network.AddressSpaces);
                    Assert.Contains("10.0.0.0/28", network.AddressSpaces);

                    // Verify subnets
                    Assert.Equal(2, network.Subnets.Count);
                    Assert.True(network.Subnets.ContainsKey("subnetA"));

                    ISubnet subnet = network.Subnets["subnetA"];
                    Assert.Equal("10.0.0.0/29", subnet.AddressPrefix);

                    Assert.True(network.Subnets.ContainsKey("subnetB"));
                    subnet = network.Subnets["subnetB"];
                    Assert.Equal("10.0.0.8/29", subnet.AddressPrefix);
                    Assert.NotNull(subnet.ServicesWithAccess);
                    Assert.True(subnet.ServicesWithAccess.ContainsKey(ServiceEndpointType.MicrosoftStorage));
                    Assert.True(subnet.ServicesWithAccess[ServiceEndpointType.MicrosoftStorage].Count > 0);

                    network = network.Update()
                              .WithTag("tag1", "value1")
                              .WithTag("tag2", "value2")
                              .WithAddressSpace("141.25.0.0/16")
                              .WithoutAddressSpace("10.1.0.0/28")
                              .WithSubnet("subnetC", "141.25.0.0/29")
                              .WithoutSubnet("subnetA")
                              .UpdateSubnet("subnetB")
                              .WithAddressPrefix("141.25.0.8/29")
                              .WithoutAccessFromService(ServiceEndpointType.MicrosoftStorage)
                              .Parent()
                              .DefineSubnet("subnetD")
                              .WithAddressPrefix("141.25.0.16/29")
                              .WithAccessFromService(ServiceEndpointType.MicrosoftStorage)
                              .Attach()
                              .Apply();

                    Assert.True(network.Tags.ContainsKey("tag1"));

                    // Verify address spaces
                    Assert.Equal(2, network.AddressSpaces.Count);
                    Assert.DoesNotContain("10.1.0.0/28", network.AddressSpaces);

                    // Verify subnets
                    Assert.Equal(3, network.Subnets.Count);
                    Assert.False(network.Subnets.ContainsKey("subnetA"));

                    Assert.True(network.Subnets.ContainsKey("subnetB"));
                    subnet = network.Subnets["subnetB"];
                    Assert.NotNull(subnet);
                    Assert.Equal("141.25.0.8/29", subnet.AddressPrefix);
                    Assert.NotNull(subnet.ServicesWithAccess);
                    Assert.Empty(subnet.ServicesWithAccess);

                    Assert.True(network.Subnets.ContainsKey("subnetC"));
                    subnet = network.Subnets["subnetC"];
                    Assert.NotNull(subnet);
                    Assert.Equal("141.25.0.0/29", subnet.AddressPrefix);

                    Assert.True(network.Subnets.ContainsKey("subnetD"));
                    subnet = network.Subnets["subnetD"];
                    Assert.NotNull(subnet);
                    Assert.Equal("141.25.0.16/29", subnet.AddressPrefix);
                    Assert.NotNull(subnet.ServicesWithAccess);
                    Assert.True(subnet.ServicesWithAccess.ContainsKey(ServiceEndpointType.MicrosoftStorage));
                    manager.ResourceManager.ResourceGroups.DeleteByName(groupName);
                }
                finally
                {
                    try
                    {
                        TestHelper.CreateResourceManager().ResourceGroups.DeleteByName(groupName);
                    }
                    catch { }
                }
            }
        }
Exemplo n.º 27
0
 internal bool MapsTo(ISubnet aSubnet)
 {
     return (aSubnet == iSubnet);
 }
Exemplo n.º 28
0
        public void CreateUpdate()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                var testId = TestUtilities.GenerateName("");

                string newName   = "net" + testId;
                var    region    = Region.USWest;
                var    groupName = "rg" + testId;

                try
                {
                    // Create an NSG
                    var manager = TestHelper.CreateNetworkManager();
                    var nsg     = manager.NetworkSecurityGroups.Define("nsg" + testId)
                                  .WithRegion(region)
                                  .WithNewResourceGroup(groupName)
                                  .Create();

                    // Create a network
                    INetwork network = manager.Networks.Define(newName)
                                       .WithRegion(region)
                                       .WithNewResourceGroup(groupName)
                                       .WithAddressSpace("10.0.0.0/28")
                                       .WithAddressSpace("10.1.0.0/28")
                                       .WithSubnet("subnetA", "10.0.0.0/29")
                                       .DefineSubnet("subnetB")
                                       .WithAddressPrefix("10.0.0.8/29")
                                       .WithExistingNetworkSecurityGroup(nsg)
                                       .Attach()
                                       .Create();

                    // Verify address spaces
                    Assert.Equal(2, network.AddressSpaces.Count);
                    Assert.Contains("10.1.0.0/28", network.AddressSpaces);

                    // Verify subnets
                    Assert.Equal(2, network.Subnets.Count);
                    ISubnet subnet = network.Subnets["subnetA"];
                    Assert.Equal("10.0.0.0/29", subnet.AddressPrefix);
                    subnet = network.Subnets["subnetB"];
                    Assert.Equal("10.0.0.8/29", subnet.AddressPrefix);
                    Assert.Equal(nsg.Id, subnet.NetworkSecurityGroupId, ignoreCase: true);

                    // Verify NSG
                    var subnets = nsg.Refresh().ListAssociatedSubnets();
                    Assert.Equal(1, subnets.Count);
                    subnet = subnets[0];
                    Assert.Equal("subnetB", subnet.Name, ignoreCase: true);
                    Assert.Equal(subnet.Parent.Name, newName, ignoreCase: true);
                    Assert.NotNull(subnet.NetworkSecurityGroupId);
                    INetworkSecurityGroup nsg2 = subnet.GetNetworkSecurityGroup();
                    Assert.NotNull(nsg2);
                    Assert.Equal(nsg2.Id, nsg.Id, ignoreCase: true);

                    network = manager.Networks.GetByResourceGroup(groupName, newName);
                    network = network.Update()
                              .WithTag("tag1", "value1")
                              .WithTag("tag2", "value2")
                              .WithAddressSpace("141.25.0.0/16")
                              .WithoutAddressSpace("10.1.0.0/28")
                              .WithSubnet("subnetC", "141.25.0.0/29")
                              .WithoutSubnet("subnetA")
                              .UpdateSubnet("subnetB")
                              .WithAddressPrefix("141.25.0.8/29")
                              .WithoutNetworkSecurityGroup()
                              .Parent()
                              .DefineSubnet("subnetD")
                              .WithAddressPrefix("141.25.0.16/29")
                              .WithExistingNetworkSecurityGroup(nsg)
                              .Attach()
                              .Apply();

                    // Verify address spaces
                    Assert.Equal(2, network.AddressSpaces.Count);
                    Assert.DoesNotContain("10.1.0.0/28", network.AddressSpaces);

                    // Verify subnets
                    Assert.Equal(3, network.Subnets.Count);
                    Assert.False(network.Subnets.ContainsKey("subnetA"));

                    Assert.True(network.Subnets.ContainsKey("subnetB"));
                    subnet = network.Subnets["subnetB"];
                    Assert.Equal("141.25.0.8/29", subnet.AddressPrefix);
                    Assert.Null(subnet.NetworkSecurityGroupId);

                    Assert.True(network.Subnets.ContainsKey("subnetC"));
                    subnet = network.Subnets["subnetC"];
                    Assert.Equal("141.25.0.0/29", subnet.AddressPrefix);
                    Assert.Null(subnet.NetworkSecurityGroupId);

                    Assert.True(network.Subnets.ContainsKey("subnetD"));
                    subnet = network.Subnets["subnetD"];
                    Assert.NotNull(subnet);
                    Assert.Equal("141.25.0.16/29", subnet.AddressPrefix);
                    Assert.Equal(nsg.Id, subnet.NetworkSecurityGroupId, ignoreCase: true);

                    Assert.True(network.Tags.ContainsKey("tag1"));

                    manager.Networks.DeleteById(network.Id);
                    manager.NetworkSecurityGroups.DeleteById(nsg.Id);
                    manager.ResourceManager.ResourceGroups.BeginDeleteByName(groupName);
                }
                finally
                {
                    try
                    {
                        TestHelper.CreateResourceManager().ResourceGroups.DeleteByName(groupName);
                    }
                    catch { }
                }
            }
        }
        /**
         * Azure sample for applying locks to resources
         *
         * Summary ...
         *
         * This sample shows examples of management locks usage on various resources.
         *
         * Details ...
         *
         * 1. Create a number of various resources to apply locks to...
         * 2. Apply various locks to the resources
         * 3. Retrieve and show lock information
         * 4. Remove the locks and clean up
         */

        public static void RunSample(IAzure azure)
        {
            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
            {
                //=============================================================
                // Create a shared resource group for all the resources so they can all be deleted together
                //
                resourceGroup = azure.ResourceGroups.Define(rgName)
                                .WithRegion(region)
                                .Create();
                Utilities.Log("Created a new resource group - " + resourceGroup.Id);

                //============================================================
                // Create various resources for demonstrating locks
                //

                // Define a network to apply a lock to
                ICreatable <INetwork> netDefinition = azure.Networks.Define(netName)
                                                      .WithRegion(region)
                                                      .WithExistingResourceGroup(resourceGroup)
                                                      .WithAddressSpace("10.0.0.0/28");

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

                // Define a VM to apply a lock to
                ICreatable <IVirtualMachine> vmDefinition = azure.VirtualMachines.Define(vmName)
                                                            .WithRegion(region)
                                                            .WithExistingResourceGroup(resourceGroup)
                                                            .WithNewPrimaryNetwork(netDefinition)
                                                            .WithPrimaryPrivateIPAddressDynamic()
                                                            .WithoutPrimaryPublicIPAddress()
                                                            .WithPopularWindowsImage(KnownWindowsVirtualMachineImage.WindowsServer2012Datacenter)
                                                            .WithAdminUsername("tester")
                                                            .WithAdminPassword(password)
                                                            .WithNewDataDisk(diskDefinition, 1, CachingTypes.None)
                                                            .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"));

                // Define a storage account to apply a lock to
                ICreatable <IStorageAccount> storageDefinition = azure.StorageAccounts.Define(storageName)
                                                                 .WithRegion(region)
                                                                 .WithExistingResourceGroup(resourceGroup);

                // Create resources in parallel to save time
                Utilities.Log("Creating the needed resources...");
                Task.WaitAll(
                    storageDefinition.CreateAsync(),
                    vmDefinition.CreateAsync());
                Utilities.Log("Resources created.");

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

                //============================================================
                // Create various locks for the created resources
                //

                // Locks can be created serially, and multiple can be applied to the same resource:
                Utilities.Log("Creating locks sequentially...");

                // Apply a ReadOnly lock to the disk
                lockDiskRO = azure.ManagementLocks.Define("diskLockRO")
                             .WithLockedResource(disk)
                             .WithLevel(LockLevel.ReadOnly)
                             .Create();

                // Apply a lock preventing the disk from being deleted
                lockDiskDel = azure.ManagementLocks.Define("diskLockDel")
                              .WithLockedResource(disk)
                              .WithLevel(LockLevel.CanNotDelete)
                              .Create();

                // Locks can also be created in parallel, for better overall performance:
                Utilities.Log("Creating locks in parallel...");

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

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

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

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

                var created = azure.ManagementLocks.Create(
                    lockVMDef,
                    lockGroupDef,
                    lockStorageDef,
                    lockSubnetDef);

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

                Utilities.Log("Locks created.");

                //============================================================
                // Retrieve and show lock information
                //

                // Count and show locks (Note: locks returned for a resource include the locks for its resource group and child resources)
                int lockCount = azure.ManagementLocks.ListForResource(vm.Id).Count();
                Utilities.Log("Number of locks applied to the virtual machine: " + lockCount);
                lockCount = azure.ManagementLocks.ListByResourceGroup(resourceGroup.Name).Count();
                Utilities.Log("Number of locks applied to the resource group (includes locks on resources in the group): " + lockCount);
                lockCount = azure.ManagementLocks.ListForResource(storage.Id).Count();
                Utilities.Log("Number of locks applied to the storage account: " + lockCount);
                lockCount = azure.ManagementLocks.ListForResource(disk.Id).Count();
                Utilities.Log("Number of locks applied to the managed disk: " + lockCount);
                lockCount = azure.ManagementLocks.ListForResource(network.Id).Count();
                Utilities.Log("Number of locks applied to the network (including its subnets): " + lockCount);

                // Locks can be retrieved using their ID
                lockVM      = azure.ManagementLocks.GetById(lockVM.Id);
                lockGroup   = azure.ManagementLocks.GetByResourceGroup(resourceGroup.Name, "rglock");
                lockStorage = azure.ManagementLocks.GetById(lockStorage.Id);
                lockDiskRO  = azure.ManagementLocks.GetById(lockDiskRO.Id);
                lockDiskDel = azure.ManagementLocks.GetById(lockDiskDel.Id);
                lockSubnet  = azure.ManagementLocks.GetById(lockSubnet.Id);

                // Show the locks
                Utilities.Print(lockGroup);
                Utilities.Print(lockVM);
                Utilities.Print(lockDiskDel);
                Utilities.Print(lockDiskRO);
                Utilities.Print(lockStorage);
                Utilities.Print(lockSubnet);

                // List all locks within a subscription
                var locksSubscription = azure.ManagementLocks.List();
                Utilities.Log("Total number of locks within this subscription: " + locksSubscription.Count());
            }
            finally
            {
                try
                {
                    // Clean up (remember to unlock resources before deleting the resource group)
                    azure.ManagementLocks.DeleteByIds(
                        lockGroup.Id,
                        lockVM.Id,
                        lockDiskRO.Id,
                        lockDiskDel.Id,
                        lockStorage.Id,
                        lockSubnet.Id);
                    Utilities.Log("Starting the deletion of the 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);
                }
            }
        }
 /// <summary>
 /// Specifies an existing private subnet to receive network traffic from.
 /// If this load balancer already has a frontend referencing this subnet, that is the frontend that will be used.
 /// Else, an automatically named new private frontend will be created implicitly on the load balancer.
 /// </summary>
 /// <param name="subnet">An existing subnet.</param>
 /// <return>The next stage of the definition.</return>
 LoadBalancerInboundNatRule.Definition.IWithFrontendPort <LoadBalancer.Definition.IWithCreateAndInboundNatRule> HasFrontend.Definition.IWithFrontend <LoadBalancerInboundNatRule.Definition.IWithFrontendPort <LoadBalancer.Definition.IWithCreateAndInboundNatRule> > .FromExistingSubnet(ISubnet subnet)
 {
     return(this.FromExistingSubnet(subnet));
 }
 /// <summary>
 /// Specifies an existing private subnet to receive network traffic from.
 /// If this load balancer already has a frontend referencing this subnet, that is the frontend that will be used.
 /// Else, an automatically named new private frontend will be created implicitly on the load balancer.
 /// </summary>
 /// <param name="subnet">An existing subnet.</param>
 /// <return>The next stage of the definition.</return>
 LoadBalancerInboundNatRule.UpdateDefinition.IWithFrontendPort <LoadBalancer.Update.IUpdate> HasFrontend.UpdateDefinition.IWithFrontend <LoadBalancerInboundNatRule.UpdateDefinition.IWithFrontendPort <LoadBalancer.Update.IUpdate> > .FromExistingSubnet(ISubnet subnet)
 {
     return(this.FromExistingSubnet(subnet));
 }
Exemplo n.º 32
0
 public void SubnetRemoved(ISubnet aSubnet)
 {
     Console.WriteLine("Removed {0}:{1}", aSubnet.Address, aSubnet.AdapterName);
 }
Exemplo n.º 33
0
 internal void Changed(ISubnet aSubnet)
 {
     foreach (Subnet subnet in iList)
     {
         if (subnet.MapsTo(aSubnet))
         {
             subnet.Changed();
             return;
         }
     }
 }
Exemplo n.º 34
0
        internal void Removed(ISubnet aSubnet)
        {
            /* Do nothing on subnet removal
             *  - probably better to present users with a list of all the subnets they have had around since turning on
             *  - definitely better on closing down - all subnets are removed but we don't want the combobox to end up setting our configured subnet to 0 in the process
             */
            /*
            int index = 0;

            foreach (Subnet subnet in iList)
            {
                if (subnet.MapsTo(aSubnet))
                {
                    iList.Remove(subnet);

                    if (CollectionChanged != null)
                    {
                        CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, subnet, index));
                    }

                    if (CountChanged != null)
                    {
                        CountChanged(this, EventArgs.Empty);
                    }

                    return;
                }

                index++;
            }
            */
        }
Exemplo n.º 35
0
 public void SubnetRemoved(ISubnet aSubnet)
 {
     Console.WriteLine("Removed {0}:{1}", aSubnet.Address, aSubnet.AdapterName);
 }
Exemplo n.º 36
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.º 37
0
        public void CreateUpdatePeering()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                var    testId       = TestUtilities.GenerateName("");
                Region region       = Region.USEast;
                string groupName    = "rg" + testId;
                string networkName  = "netA" + testId;
                string networkName2 = "netB" + testId;
                var    networks     = TestHelper.CreateNetworkManager().Networks;

                try
                {
                    // Create networks
                    ICreatable <INetwork> remoteNetworkDefinition = networks.Define(networkName2)
                                                                    .WithRegion(region)
                                                                    .WithNewResourceGroup(groupName)
                                                                    .WithAddressSpace("10.1.0.0/27")
                                                                    .WithSubnet("subnet3", "10.1.0.0/27");

                    ICreatable <INetwork> localNetworkDefinition = networks.Define(networkName)
                                                                   .WithRegion(region)
                                                                   .WithNewResourceGroup(groupName)
                                                                   .WithAddressSpace("10.0.0.0/27")
                                                                   .WithSubnet("subnet1", "10.0.0.0/28")
                                                                   .WithSubnet("subnet2", "10.0.0.16/28");

                    var      createdNetworks = networks.Create(remoteNetworkDefinition, localNetworkDefinition);
                    INetwork localNetwork    = createdNetworks.FirstOrDefault(o => o.Key == localNetworkDefinition.Key);
                    Assert.NotNull(localNetwork);
                    INetwork remoteNetwork = createdNetworks.FirstOrDefault(o => o.Key == remoteNetworkDefinition.Key);
                    Assert.NotNull(remoteNetwork);

                    // Create peering
                    INetworkPeering localPeering = localNetwork.Peerings.Define("peer0")
                                                   .WithRemoteNetwork(remoteNetwork)

                                                   // Optionals
                                                   .WithTrafficForwardingBetweenBothNetworks()
                                                   .WithoutAccessFromEitherNetwork()
                                                   .WithGatewayUseByRemoteNetworkAllowed()
                                                   .Create();

                    // Verify local peering
                    Assert.NotNull(localNetwork.Peerings);
                    var localPeerings = localNetwork.Peerings.List();
                    Assert.Single(localPeerings);
                    localPeering = localPeerings.FirstOrDefault();
                    Assert.NotNull(localPeering);
                    Assert.Equal("peer0", localPeering.Name, true);
                    Assert.Equal(VirtualNetworkPeeringState.Connected, localPeering.State);
                    Assert.True(localPeering.IsTrafficForwardingFromRemoteNetworkAllowed);
                    Assert.False(localPeering.CheckAccessBetweenNetworks());
                    Assert.Equal(NetworkPeeringGatewayUse.ByRemoteNetwork, localPeering.GatewayUse);

                    // Verify remote peering
                    Assert.NotNull(remoteNetwork.Peerings);
                    Assert.Single(remoteNetwork.Peerings.List());
                    INetworkPeering remotePeering = localPeering.GetRemotePeering();
                    Assert.NotNull(remotePeering);
                    Assert.Equal(localNetwork.Id, remotePeering.RemoteNetworkId, true);
                    Assert.Equal(VirtualNetworkPeeringState.Connected, remotePeering.State);
                    Assert.True(remotePeering.IsTrafficForwardingFromRemoteNetworkAllowed);
                    Assert.False(remotePeering.CheckAccessBetweenNetworks());
                    Assert.Equal(NetworkPeeringGatewayUse.None, remotePeering.GatewayUse);

                    // Update peering
                    localPeering = localNetwork.Peerings.List().FirstOrDefault();
                    Assert.NotNull(localPeering);

                    // Verify remote IP invisibility to local network before peering
                    remoteNetwork = localPeering.GetRemoteNetwork();
                    Assert.NotNull(remoteNetwork);
                    ISubnet remoteSubnet = remoteNetwork.Subnets["subnet3"];
                    Assert.NotNull(remoteSubnet);
                    var remoteAvailableIPs = remoteSubnet.ListAvailablePrivateIPAddresses();
                    Assert.NotNull(remoteAvailableIPs);
                    Assert.NotEmpty(remoteAvailableIPs);
                    string remoteTestIP = remoteAvailableIPs.FirstOrDefault();
                    Assert.False(localNetwork.IsPrivateIPAddressAvailable(remoteTestIP));

                    localPeering.Update()
                    .WithoutTrafficForwardingFromEitherNetwork()
                    .WithAccessBetweenBothNetworks()
                    .WithoutAnyGatewayUse()
                    .Apply();

                    // Verify local peering changes
                    Assert.False(localPeering.IsTrafficForwardingFromRemoteNetworkAllowed);
                    Assert.True(localPeering.CheckAccessBetweenNetworks());
                    Assert.Equal(NetworkPeeringGatewayUse.None, localPeering.GatewayUse);

                    // Verify remote peering changes
                    remotePeering = localPeering.GetRemotePeering();
                    Assert.NotNull(remotePeering);
                    Assert.False(remotePeering.IsTrafficForwardingFromRemoteNetworkAllowed);
                    Assert.True(remotePeering.CheckAccessBetweenNetworks());
                    Assert.Equal(NetworkPeeringGatewayUse.None, remotePeering.GatewayUse);

                    // Delete the peering
                    localNetwork.Peerings.DeleteById(remotePeering.Id);

                    // Verify deletion
                    Assert.Empty(localNetwork.Peerings.List());
                    Assert.Empty(remoteNetwork.Peerings.List());

                    // Cleanup
                    networks.Manager.ResourceManager.ResourceGroups.BeginDeleteByName(groupName);
                }
                finally
                {
                    try
                    {
                        TestHelper.CreateResourceManager().ResourceGroups.DeleteByName(groupName);
                    }
                    catch { }
                }
            }
        }