Пример #1
0
        public void Subnet_ShouldHave_ID_SiteID_Network_Description_Netmask_Gateway_Preference()
        {
            Subnet s = new Subnet(1, 1, "192.168.4.0","Main LAN","255.255.255.0","192.168.4.200",1);

            Assert.AreEqual(1, s.SubnetId);
            Assert.AreEqual(1, s.SiteId);
            Assert.AreEqual("192.168.4.0", s.Network);
            Assert.AreEqual("Main LAN", s.Description);
            Assert.AreEqual("255.255.255.0",s.Netmask);
            Assert.AreEqual("192.168.4.200", s.Gateway);
            Assert.AreEqual(1, s.Preference);
        }
Пример #2
0
        public IQueryable<Subnet> GetSubnets()
        {
            IList<Subnet> result = new List<Subnet>();

            for (int i = 1; i<=2; i++)
            {
                Subnet s = new Subnet();
                s.SubnetId = i;
                s.SiteId = 1;
                s.Network = "192.168." + i + ".0";
                s.Description = "TestSubnet" + i;
                s.Netmask = "255.255.255.0";
                s.Gateway = "192.168." + i + ".1";
                s.Preference = i;
                result.Add(s);
            }
            return result.AsQueryable<Subnet>();
        }
Пример #3
0
        public Func <RegionalContext, IRegionalEndpoint> BuildVMScaleSetApp(GlobalContext context)
        {
            var options =
                CustomResourceOptions.Merge(context.Options, new CustomResourceOptions {
                DeleteBeforeReplace = true
            });
            var file = File.ReadAllText("./vm/vmCustomData.yaml");

            return((RegionalContext region) =>
            {
                var location = region.Location;
                var domainName = $"rnddnplm{location}"; //TODO: random

                var publicIp = new PublicIp($"pip-{location}", new PublicIpArgs
                {
                    ResourceGroupName = resourceGroup.Name,
                    Location = location,
                    AllocationMethod = "Static",
                    DomainNameLabel = domainName,
                },
                                            options);

                var loadBalancer = new LoadBalancer($"lb-{location}", new LoadBalancerArgs
                {
                    ResourceGroupName = resourceGroup.Name,
                    Location = location,
                    FrontendIpConfigurations =
                    {
                        new LoadBalancerFrontendIpConfigurationArgs
                        {
                            Name = "PublicIPAddress",
                            PublicIpAddressId = publicIp.Id,
                        }
                    }
                },
                                                    options);

                var bpepool = new BackendAddressPool($"bap-{location}", new BackendAddressPoolArgs
                {
                    ResourceGroupName = resourceGroup.Name,
                    LoadbalancerId = loadBalancer.Id,
                },
                                                     options);

                var probe = new Probe($"ssh-probe-{location}".Truncate(16), new ProbeArgs
                {
                    ResourceGroupName = resourceGroup.Name,
                    LoadbalancerId = loadBalancer.Id,
                    Port = 80,
                },
                                      options);

                var rule = new Rule($"rule-{location}", new RuleArgs
                {
                    ResourceGroupName = resourceGroup.Name,
                    BackendAddressPoolId = bpepool.Id,
                    BackendPort = 80,
                    FrontendIpConfigurationName = "PublicIPAddress",
                    FrontendPort = 80,
                    LoadbalancerId = loadBalancer.Id,
                    ProbeId = probe.Id,
                    Protocol = "Tcp",
                },
                                    options);

                var vnet = new VirtualNetwork($"vnet-{location}", new VirtualNetworkArgs
                {
                    ResourceGroupName = resourceGroup.Name,
                    Location = location,
                    AddressSpaces = { "10.0.0.0/16" },
                },
                                              options);

                var subnet = new Subnet($"subnet-{location}", new SubnetArgs
                {
                    ResourceGroupName = resourceGroup.Name,
                    AddressPrefix = "10.0.2.0/24",
                    VirtualNetworkName = vnet.Name,
                },
                                        options);

                var customData = Output.All <string>(context.CosmosAccount.Endpoint,
                                                     context.CosmosAccount.PrimaryMasterKey, context.Database.Name, context.Container.Name)
                                 .Apply(values =>
                {
                    return file.Replace("${ENDPOINT}", values[0])
                    .Replace("${MASTER_KEY}", values[1])
                    .Replace("${DATABASE}", values[2])
                    .Replace("${COLLECTION}", values[3])
                    .Replace("${LOCATION}", location);
                });

                var scaleSet = new ScaleSet($"vmss-{location}", new ScaleSetArgs
                {
                    ResourceGroupName = resourceGroup.Name,
                    Location = location,
                    NetworkProfiles =
                    {
                        new ScaleSetNetworkProfileArgs
                        {
                            IpConfigurations =
                            {
                                new ScaleSetNetworkProfileIpConfigurationArgs
                                {
                                    LoadBalancerBackendAddressPoolIds ={ bpepool.Id                                         },
                                    Name = "IPConfiguration",
                                    Primary = true,
                                    SubnetId = subnet.Id,
                                }
                            },
                            Name = "networkprofile",
                            Primary = true,
                        }
                    },
                    OsProfile = new ScaleSetOsProfileArgs
                    {
                        AdminUsername = "******",
                        AdminPassword = "******",
                        ComputerNamePrefix = "lab",
                        CustomData = customData,
                    },
                    OsProfileLinuxConfig = new ScaleSetOsProfileLinuxConfigArgs
                    {
                        DisablePasswordAuthentication = false
                    },
                    Sku = new ScaleSetSkuArgs
                    {
                        Capacity = 1,
                        Name = "Standard_DS1_v2",
                        Tier = "Standard",
                    },
                    StorageProfileDataDisks =
                    {
                        new ScaleSetStorageProfileDataDiskArgs
                        {
                            Caching = "ReadWrite",
                            CreateOption = "Empty",
                            DiskSizeGb = 10,
                            Lun = 0,
                        }
                    },
                    StorageProfileImageReference = new ScaleSetStorageProfileImageReferenceArgs
                    {
                        Offer = "UbuntuServer",
                        Publisher = "Canonical",
                        Sku = "18.04-LTS",
                        Version = "latest",
                    },
                    StorageProfileOsDisk = new ScaleSetStorageProfileOsDiskArgs
                    {
                        Caching = "ReadWrite",
                        CreateOption = "FromImage",
                        ManagedDiskType = "Standard_LRS",
                        Name = "",
                    },
                    UpgradePolicyMode = "Automatic",
                },
                                            CustomResourceOptions.Merge(options, new CustomResourceOptions {
                    DependsOn = { bpepool, rule }
                }));

                var autoscale = new AutoscaleSetting($"as-{location}", new AutoscaleSettingArgs
                {
                    ResourceGroupName = resourceGroup.Name,
                    Location = location,
                    Notification = new AutoscaleSettingNotificationArgs
                    {
                        Email = new AutoscaleSettingNotificationEmailArgs
                        {
                            CustomEmails = { "*****@*****.**" },
                            SendToSubscriptionAdministrator = true,
                            SendToSubscriptionCoAdministrator = true,
                        },
                    },
                    Profiles =
                    {
                        new AutoscaleSettingProfileArgs
                        {
                            Capacity = new AutoscaleSettingProfileCapacityArgs
                            {
                                Default = 1,
                                Maximum = 10,
                                Minimum = 1,
                            },
                            Name = "defaultProfile",
                            Rules =
                            {
                                new AutoscaleSettingProfileRuleArgs
                                {
                                    MetricTrigger = new AutoscaleSettingProfileRuleMetricTriggerArgs
                                    {
                                        MetricName = "Percentage CPU",
                                        MetricResourceId = scaleSet.Id,
                                        Operator = "GreaterThan",
                                        Statistic = "Average",
                                        Threshold = 75,
                                        TimeAggregation = "Average",
                                        TimeGrain = "PT1M",
                                        TimeWindow = "PT5M",
                                    },
                                    ScaleAction = new AutoscaleSettingProfileRuleScaleActionArgs
                                    {
                                        Cooldown = "PT1M",
                                        Direction = "Increase",
                                        Type = "ChangeCount",
                                        Value = 1,
                                    },
                                },
                                new AutoscaleSettingProfileRuleArgs
                                {
                                    MetricTrigger = new AutoscaleSettingProfileRuleMetricTriggerArgs
                                    {
                                        MetricName = "Percentage CPU",
                                        MetricResourceId = scaleSet.Id,
                                        Operator = "LessThan",
                                        Statistic = "Average",
                                        Threshold = 25,
                                        TimeAggregation = "Average",
                                        TimeGrain = "PT1M",
                                        TimeWindow = "PT5M",
                                    },
                                    ScaleAction = new AutoscaleSettingProfileRuleScaleActionArgs
                                    {
                                        Cooldown = "PT1M",
                                        Direction = "Decrease",
                                        Type = "ChangeCount",
                                        Value = 1,
                                    },
                                },
                            }
                        }
                    },
                    TargetResourceId = scaleSet.Id,
                },
                                                     options);

                return new AzureEndpoint(publicIp.Id);
            });
        }
        private async Task CreateVmsAsync(ResourceGroup resourceGroup, AvailabilitySet aset, Subnet subnet)
        {
            var computeClient = new ComputeManagementClient(Context.SubscriptionId, Context.Credential);
            var networkClient = new NetworkManagementClient(Context.SubscriptionId, Context.Credential);

            for (int i = 0; i < 10; i++)
            {
                var vmName = $"{Context.VmName}_{i}";
                // Create IP Address
                Console.WriteLine("--------Start create IP Address--------");
                var ipAddress = new PublicIPAddress()
                {
                    PublicIPAddressVersion   = Azure.ResourceManager.Network.Models.IPVersion.IPv4.ToString(),
                    PublicIPAllocationMethod = IPAllocationMethod.Dynamic,
                    Location = Context.Loc,
                };

                ipAddress = await networkClient.PublicIPAddresses.StartCreateOrUpdate(resourceGroup.Name, $"{vmName}_ip", ipAddress).WaitForCompletionAsync();

                // Create Network Interface
                Console.WriteLine("--------Start create Network Interface--------");
                var nic = new NetworkInterface()
                {
                    Location         = Context.Loc,
                    IpConfigurations = new List <NetworkInterfaceIPConfiguration>()
                    {
                        new NetworkInterfaceIPConfiguration()
                        {
                            Name    = "Primary",
                            Primary = true,
                            Subnet  = new Subnet()
                            {
                                Id = subnet.Id
                            },
                            PrivateIPAllocationMethod = IPAllocationMethod.Dynamic,
                            PublicIPAddress           = new PublicIPAddress()
                            {
                                Id = ipAddress.Id
                            }
                        }
                    }
                };

                nic = await networkClient.NetworkInterfaces.StartCreateOrUpdate(resourceGroup.Name, $"{vmName}_nic", nic).WaitForCompletionAsync();

                // Create VM
                string num  = i % 2 == 0 ? "even" : "odd";
                string name = $"{vmName}-{num}";
                Console.WriteLine("--------Start create VM {0}--------", i);
                var vm = new VirtualMachine(Context.Loc)
                {
                    NetworkProfile = new Azure.ResourceManager.Compute.Models.NetworkProfile {
                        NetworkInterfaces = new[] { new NetworkInterfaceReference()
                                                    {
                                                        Id = nic.Id
                                                    } }
                    },
                    OsProfile = new OSProfile
                    {
                        ComputerName       = name,
                        AdminUsername      = "******",
                        AdminPassword      = "******",
                        LinuxConfiguration = new LinuxConfiguration {
                            DisablePasswordAuthentication = false, ProvisionVMAgent = true
                        }
                    },
                    StorageProfile = new StorageProfile()
                    {
                        ImageReference = new ImageReference()
                        {
                            Offer     = "UbuntuServer",
                            Publisher = "Canonical",
                            Sku       = "18.04-LTS",
                            Version   = "latest"
                        },
                        DataDisks = new List <DataDisk>()
                    },
                    HardwareProfile = new HardwareProfile()
                    {
                        VmSize = VirtualMachineSizeTypes.StandardB1Ms
                    },
                    // The namespace-qualified type for SubResource is needed because all 3 libraries define an identical SubResource type. In the proposed model, the common type would be part of the core library
                    AvailabilitySet = new Azure.ResourceManager.Compute.Models.SubResource()
                    {
                        Id = aset.Id
                    }
                };
                vm = await computeClient.VirtualMachines.StartCreateOrUpdate(Context.RgName, Context.VmName, vm).WaitForCompletionAsync();
            }
        }
Пример #5
0
        public static IPAddress[] ConvertIPRangeToIPAddresses(string[] ipRanges, CancellationToken cancellationToken)
        {
            ConcurrentBag <IPAddress> bag = new ConcurrentBag <IPAddress>();

            ParallelOptions parallelOptions = new ParallelOptions()
            {
                CancellationToken = cancellationToken
            };

            foreach (string ipOrRange in ipRanges)
            {
                // Match 192.168.0.1
                if (Regex.IsMatch(ipOrRange, RegexHelper.IPv4AddressRegex))
                {
                    bag.Add(IPAddress.Parse(ipOrRange));
                    continue;
                }

                // Match 192.168.0.0/24 or 192.168.0.0/255.255.255.0
                if (Regex.IsMatch(ipOrRange, RegexHelper.IPv4AddressCidrRegex) || Regex.IsMatch(ipOrRange, RegexHelper.IPv4AddressSubnetmaskRegex))
                {
                    string[] subnet = ipOrRange.Split('/');

                    IPAddress ip         = IPAddress.Parse(subnet[0]);
                    IPAddress subnetmask = int.TryParse(subnet[1], out int cidr) ? IPAddress.Parse(Subnetmask.ConvertCidrToSubnetmask(cidr)) : IPAddress.Parse(subnet[1]);

                    IPAddress networkAddress = Subnet.GetIPv4NetworkAddress(ip, subnetmask);
                    IPAddress broadcast      = Subnet.GetIPv4Broadcast(ip, subnetmask);

                    Parallel.For(IPv4AddressHelper.ConvertToInt32(networkAddress), IPv4AddressHelper.ConvertToInt32(broadcast) + 1, parallelOptions, i =>
                    {
                        bag.Add(IPv4AddressHelper.ConvertFromInt32(i));

                        parallelOptions.CancellationToken.ThrowIfCancellationRequested();
                    });

                    continue;
                }

                // Match 192.168.0.0 - 192.168.0.100
                if (Regex.IsMatch(ipOrRange, RegexHelper.IPv4AddressRangeRegex))
                {
                    string[] range = ipOrRange.Split('-');

                    Parallel.For(IPv4AddressHelper.ConvertToInt32(IPAddress.Parse(range[0])), IPv4AddressHelper.ConvertToInt32(IPAddress.Parse(range[1])) + 1, parallelOptions, i =>
                    {
                        bag.Add(IPv4AddressHelper.ConvertFromInt32(i));

                        parallelOptions.CancellationToken.ThrowIfCancellationRequested();
                    });

                    continue;
                }

                // Convert 192.168.[50-100,200].1 to 192.168.50.1, 192.168.51.1, 192.168.52.1, {..}, 192.168.200.1
                if (Regex.IsMatch(ipOrRange, RegexHelper.IPv4AddressSpecialRangeRegex))
                {
                    string[] octets = ipOrRange.Split('.');

                    List <List <int> > list = new List <List <int> >();

                    // Go through each octet...
                    for (int i = 0; i < octets.Length; i++)
                    {
                        List <int> innerList = new List <int>();

                        // Create a range for each octet
                        if (Regex.IsMatch(octets[i], RegexHelper.SpecialRangeRegex))
                        {
                            foreach (string numberOrRange in octets[i].Substring(1, octets[i].Length - 2).Split(','))
                            {
                                // 50-100
                                if (numberOrRange.Contains("-"))
                                {
                                    string[] rangeNumbers = numberOrRange.Split('-');

                                    for (int j = int.Parse(rangeNumbers[0]); j < (int.Parse(rangeNumbers[1]) + 1); j++)
                                    {
                                        innerList.Add(j);
                                    }
                                } // 200
                                else
                                {
                                    innerList.Add(int.Parse(numberOrRange));
                                }
                            }
                        }
                        else
                        {
                            innerList.Add(int.Parse(octets[i]));
                        }

                        list.Add(innerList);
                    }

                    // Build the new ipv4
                    foreach (int i in list[0])
                    {
                        foreach (int j in list[1])
                        {
                            foreach (int k in list[2])
                            {
                                foreach (int h in list[3])
                                {
                                    bag.Add(IPAddress.Parse(string.Format("{0}.{1}.{2}.{3}", i, j, k, h)));
                                }
                            }
                        }
                    }

                    continue;
                }
            }

            return(bag.ToArray());
        }
        public VirtualMachineScaleSet CreateVMScaleSet_NoAsyncTracking(
            string rgName,
            string vmssName,
            StorageAccount storageAccount,
            ImageReference imageRef,
            out VirtualMachineScaleSet inputVMScaleSet,
            VirtualMachineScaleSetExtensionProfile extensionProfile = null,
            Action <VirtualMachineScaleSet> vmScaleSetCustomizer    = null,
            bool createWithPublicIpAddress = false,
            bool createWithManagedDisks    = false,
            bool hasDiffDisks          = false,
            bool createWithHealthProbe = false,
            Subnet subnet              = null,
            IList <string> zones       = null,
            int?osDiskSizeInGB         = null,
            string ppgId               = null,
            string machineSizeType     = null,
            bool?enableUltraSSD        = false,
            string diskEncryptionSetId = null,
            AutomaticRepairsPolicy automaticRepairsPolicy = null,
            bool?encryptionAtHostEnabled = null,
            bool singlePlacementGroup    = true,
            DiagnosticsProfile bootDiagnosticsProfile = null,
            int?faultDomainCount = null,
            int?capacity         = null,
            string dedicatedHostGroupReferenceId = null,
            string dedicatedHostGroupName        = null,
            string dedicatedHostName             = null)
        {
            try
            {
                var createOrUpdateResponse = CreateVMScaleSetAndGetOperationResponse(rgName,
                                                                                     vmssName,
                                                                                     storageAccount,
                                                                                     imageRef,
                                                                                     out inputVMScaleSet,
                                                                                     extensionProfile,
                                                                                     vmScaleSetCustomizer,
                                                                                     createWithPublicIpAddress,
                                                                                     createWithManagedDisks,
                                                                                     hasDiffDisks,
                                                                                     createWithHealthProbe,
                                                                                     subnet,
                                                                                     zones,
                                                                                     osDiskSizeInGB,
                                                                                     ppgId: ppgId,
                                                                                     machineSizeType: machineSizeType,
                                                                                     enableUltraSSD: enableUltraSSD,
                                                                                     diskEncryptionSetId: diskEncryptionSetId,
                                                                                     automaticRepairsPolicy: automaticRepairsPolicy,
                                                                                     encryptionAtHostEnabled: encryptionAtHostEnabled,
                                                                                     singlePlacementGroup: singlePlacementGroup,
                                                                                     bootDiagnosticsProfile: bootDiagnosticsProfile,
                                                                                     faultDomainCount: faultDomainCount,
                                                                                     capacity: capacity,
                                                                                     dedicatedHostGroupReferenceId: dedicatedHostGroupReferenceId,
                                                                                     dedicatedHostGroupName: dedicatedHostGroupName,
                                                                                     dedicatedHostName: dedicatedHostName);

                var getResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName);

                return(getResponse);
            }
            catch
            {
                // TODO: It is better to issue Delete and forget.
                m_ResourcesClient.ResourceGroups.Delete(rgName);
                throw;
            }
        }
        public void SubnetApiTest()
        {
            var handler = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (var context = UndoContext.Current)
            {
                context.Start();
                var resourcesClient = ResourcesManagementTestUtilities.GetResourceManagementClientWithHandler(handler);
                var networkResourceProviderClient =
                    NetworkManagementTestUtilities.GetNetworkResourceProviderClient(handler);

                var location = NetworkManagementTestUtilities.GetResourceLocation(resourcesClient,
                                                                                  "Microsoft.Network/virtualNetworks");

                string resourceGroupName = TestUtilities.GenerateName("csmrg");
                resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName,
                                                              new ResourceGroup
                {
                    Location = location
                });

                string vnetName    = TestUtilities.GenerateName();
                string subnet1Name = TestUtilities.GenerateName();
                string subnet2Name = TestUtilities.GenerateName();

                var vnet = new VirtualNetwork()
                {
                    Location = location,

                    AddressSpace = new AddressSpace()
                    {
                        AddressPrefixes = new List <string>()
                        {
                            "10.0.0.0/16",
                        }
                    },
                    DhcpOptions = new DhcpOptions()
                    {
                        DnsServers = new List <string>()
                        {
                            "10.1.1.1",
                            "10.1.2.4"
                        }
                    },
                    Subnets = new List <Subnet>()
                    {
                        new Subnet()
                        {
                            Name          = subnet1Name,
                            AddressPrefix = "10.0.0.0/24",
                        }
                    }
                };

                var putVnetResponse = networkResourceProviderClient.VirtualNetworks.CreateOrUpdate(resourceGroupName, vnetName, vnet);
                Assert.Equal(HttpStatusCode.OK, putVnetResponse.StatusCode);

                // Create a Subnet
                // Populate paramters for a Subnet
                var subnet = new Subnet()
                {
                    Name          = subnet2Name,
                    AddressPrefix = "10.0.1.0/24",
                };

                #region Verification

                var putSubnetResponse = networkResourceProviderClient.Subnets.CreateOrUpdate(resourceGroupName, vnetName, subnet2Name, subnet);
                Assert.Equal(HttpStatusCode.OK, putSubnetResponse.StatusCode);

                var getVnetResponse = networkResourceProviderClient.VirtualNetworks.Get(resourceGroupName, vnetName);
                Assert.Equal(HttpStatusCode.OK, getVnetResponse.StatusCode);
                Assert.Equal(2, getVnetResponse.VirtualNetwork.Subnets.Count);

                var getSubnetResponse = networkResourceProviderClient.Subnets.Get(resourceGroupName, vnetName, subnet2Name);
                Assert.Equal(HttpStatusCode.OK, getSubnetResponse.StatusCode);

                // Verify the getSubnetResponse
                Assert.True(AreSubnetsEqual(getVnetResponse.VirtualNetwork.Subnets[1],
                                            getSubnetResponse.Subnet));

                var getSubnetListResponse = networkResourceProviderClient.Subnets.List(resourceGroupName, vnetName);
                Assert.Equal(HttpStatusCode.OK, getSubnetListResponse.StatusCode);

                // Verify ListSubnets
                Assert.True(AreSubnetsEqual(getVnetResponse.VirtualNetwork.Subnets,
                                            getSubnetListResponse.Subnets));

                // Delete the subnet "subnet1"
                var deleteSubnetResponse = networkResourceProviderClient.Subnets.Delete(resourceGroupName, vnetName, subnet2Name);
                Assert.Equal(HttpStatusCode.OK, deleteSubnetResponse.StatusCode);

                // Verify that the deletion was successful
                getSubnetListResponse = networkResourceProviderClient.Subnets.List(resourceGroupName, vnetName);
                Assert.Equal(HttpStatusCode.OK, getSubnetListResponse.StatusCode);

                Assert.Equal(1, getSubnetListResponse.Subnets.Count);
                Assert.Equal(subnet1Name, getSubnetListResponse.Subnets[0].Name);

                #endregion
            }
        }
Пример #8
0
        private VirtualMachineScaleSetNetworkProfile CreateNetworkResource(VirtualMachineScaleSetNetworkConfiguration existingNetworkConfig)
        {
            var subsetName = string.Format("Subnet-{0}", this.NodeType);

            var ipConfiguration = existingNetworkConfig.IpConfigurations.FirstOrDefault();

            if (ipConfiguration == null)
            {
                throw new PSInvalidOperationException(ServiceFabricProperties.Resources.InvalidVmssConfiguration);
            }

            var          subNetId        = ipConfiguration.Subnet.Id;
            const string virtualNetworks = "Microsoft.Network/virtualNetworks/";
            var          virtualNetwork  = string.Empty;
            int          index           = -1;

            if ((index = subNetId.IndexOf(virtualNetworks, StringComparison.OrdinalIgnoreCase)) != -1)
            {
                var end = subNetId.IndexOf("/", index + virtualNetworks.Length);
                virtualNetwork = subNetId.Substring(index + virtualNetworks.Length, end - index - virtualNetworks.Length);
            }

            if (string.IsNullOrEmpty(virtualNetwork))
            {
                throw new InvalidOperationException();
            }

            var network = NetworkManagementClient.VirtualNetworks.Get(this.ResourceGroupName, virtualNetwork);

            var    start  = 1;
            Subnet subnet = null;
            var    retry  = 5;

            while (retry-- >= 0)
            {
                try
                {
                    subnet = NetworkManagementClient.Subnets.CreateOrUpdate(
                        this.ResourceGroupName,
                        virtualNetwork,
                        string.Format("{0}-{1}", subsetName, start),
                        new Subnet()
                    {
                        AddressPrefix = string.Format("10.0.{0}.0/24", start++)
                    });

                    network.Subnets.Add(subnet);
                    network = NetworkManagementClient.VirtualNetworks.CreateOrUpdate(
                        this.ResourceGroupName,
                        virtualNetwork,
                        network);

                    this.addressPrefix = subnet.AddressPrefix;
                    break;
                }
                catch (Rest.Azure.CloudException ex)
                {
                    if (ex.Body.Code == "NetcfgInvalidSubnet" ||
                        ex.Body.Code == "InUseSubnetCannotBeUpdated")
                    {
                        network.Subnets.Remove(subnet);
                        continue;
                    }

                    if (ex.Body.Code == "InvalidRequestFormat")
                    {
                        if (ex.Body.Details != null)
                        {
                            var details = ex.Body.Details.Where(d => d.Code == "DuplicateResourceName");
                            if (details.Any())
                            {
                                network.Subnets.Remove(subnet);
                                continue;
                            }
                        }
                    }

                    throw;
                }
            }

            var publicAddressName = string.Format("LBIP-{0}-{1}{2}", this.Name.ToLower(), this.NodeType.ToLower(), index);
            var dnsLable          = string.Format("{0}-{1}{2}", this.Name.ToLower(), this.NodeType.ToLower(), index);
            var lbName            = string.Format("LB-{0}-{1}{2}", this.Name.ToLower(), this.NodeType.ToLower(), index);

            var publicIp = NetworkManagementClient.PublicIPAddresses.CreateOrUpdate(
                this.ResourceGroupName,
                publicAddressName,
                new PublicIPAddress()
            {
                PublicIPAllocationMethod = "Dynamic",
                Location    = GetLocation(),
                DnsSettings = new PublicIPAddressDnsSettings(dnsLable)
            });

            var backendAdressPollName       = "LoadBalancerBEAddressPool";
            var frontendIpConfigurationName = "LoadBalancerIPConfig";
            var probeName           = "FabricGatewayProbe";
            var probeHTTPName       = "FabricHttpGatewayProbe";
            var inboundNatPoolsName = "LoadBalancerBEAddressNatPool";

            var newLoadBalancerId = string.Format(
                LoadBalancerIdFormat,
                this.NetworkManagementClient.SubscriptionId,
                this.ResourceGroupName,
                lbName);

            var newLoadBalancer = new LoadBalancer(newLoadBalancerId, lbName)
            {
                Location = GetLocation(),
                FrontendIPConfigurations = new List <FrontendIPConfiguration>()
                {
                    new FrontendIPConfiguration()
                    {
                        Name            = frontendIpConfigurationName,
                        PublicIPAddress = new PublicIPAddress()
                        {
                            Id = publicIp.Id
                        }
                    }
                },
                BackendAddressPools = new List <BackendAddressPool>()
                {
                    new BackendAddressPool()
                    {
                        Name = backendAdressPollName
                    }
                },
                LoadBalancingRules = new List <LoadBalancingRule>()
                {
                    new LoadBalancingRule()
                    {
                        Name = "LBRule",
                        BackendAddressPool = new Management.Network.Models.SubResource()
                        {
                            Id = string.Format(
                                BackendAddressIdFormat,
                                NetworkManagementClient.SubscriptionId,
                                this.ResourceGroupName,
                                lbName,
                                backendAdressPollName)
                        },
                        BackendPort             = Constants.DefaultTcpPort,
                        EnableFloatingIP        = false,
                        FrontendIPConfiguration = new Management.Network.Models.SubResource()
                        {
                            Id = string.Format(
                                FrontendIDFormat,
                                NetworkManagementClient.SubscriptionId,
                                this.ResourceGroupName,
                                lbName,
                                frontendIpConfigurationName)
                        },
                        FrontendPort         = Constants.DefaultTcpPort,
                        IdleTimeoutInMinutes = 5,
                        Protocol             = "tcp",
                        Probe = new Management.Network.Models.SubResource()
                        {
                            Id = string.Format(
                                ProbeIDFormat,
                                NetworkManagementClient.SubscriptionId,
                                this.ResourceGroupName,
                                lbName,
                                probeName)
                        }
                    },
                    new LoadBalancingRule()
                    {
                        Name = "LBHttpRule",
                        BackendAddressPool = new Management.Network.Models.SubResource()
                        {
                            Id = string.Format(
                                BackendAddressIdFormat,
                                NetworkManagementClient.SubscriptionId,
                                this.ResourceGroupName,
                                lbName,
                                backendAdressPollName)
                        },
                        BackendPort             = Constants.DefaultHttpPort,
                        EnableFloatingIP        = false,
                        FrontendIPConfiguration = new Management.Network.Models.SubResource()
                        {
                            Id = string.Format(
                                FrontendIDFormat,
                                NetworkManagementClient.SubscriptionId,
                                this.ResourceGroupName,
                                lbName,
                                frontendIpConfigurationName)
                        },
                        FrontendPort         = Constants.DefaultHttpPort,
                        IdleTimeoutInMinutes = 5,
                        Protocol             = "tcp",
                        Probe = new Management.Network.Models.SubResource()
                        {
                            Id = string.Format(
                                ProbeIDFormat,
                                NetworkManagementClient.SubscriptionId,
                                this.ResourceGroupName,
                                lbName,
                                probeHTTPName)
                        }
                    }
                },
                Probes = new List <Probe>()
                {
                    new Probe()
                    {
                        Name = probeName,
                        IntervalInSeconds = 5,
                        NumberOfProbes    = 2,
                        Port = Constants.DefaultTcpPort
                    },
                    new Probe()
                    {
                        Name = probeHTTPName,
                        IntervalInSeconds = 5,
                        NumberOfProbes    = 2,
                        Port = Constants.DefaultHttpPort
                    },
                },
                InboundNatPools = new List <InboundNatPool>()
                {
                    new InboundNatPool()
                    {
                        Name                    = inboundNatPoolsName,
                        BackendPort             = Constants.DefaultBackendPort,
                        FrontendIPConfiguration = new Management.Network.Models.SubResource()
                        {
                            Id = string.Format(
                                FrontendIDFormat,
                                NetworkManagementClient.SubscriptionId,
                                this.ResourceGroupName,
                                lbName,
                                frontendIpConfigurationName)
                        },
                        FrontendPortRangeStart = Constants.DefaultFrontendPortRangeStart,
                        FrontendPortRangeEnd   = Constants.DefaultFrontendPortRangeEnd,
                        Protocol = "tcp"
                    }
                }
            };

            NetworkManagementClient.LoadBalancers.BeginCreateOrUpdate(
                this.ResourceGroupName,
                lbName,
                newLoadBalancer);

            newLoadBalancer = NetworkManagementClient.LoadBalancers.Get(this.ResourceGroupName, lbName);

            return(new VirtualMachineScaleSetNetworkProfile()
            {
                NetworkInterfaceConfigurations = new List <VirtualMachineScaleSetNetworkConfiguration>()
                {
                    new VirtualMachineScaleSetNetworkConfiguration()
                    {
                        IpConfigurations = new List <VirtualMachineScaleSetIPConfiguration>()
                        {
                            new VirtualMachineScaleSetIPConfiguration()
                            {
                                Name = string.Format("Nic-{0}", start),
                                LoadBalancerBackendAddressPools = newLoadBalancer.BackendAddressPools.Select(
                                    b => new Management.Compute.Models.SubResource()
                                {
                                    Id = b.Id
                                }
                                    ).ToList(),

                                LoadBalancerInboundNatPools = newLoadBalancer.InboundNatPools.Select(
                                    p => new Management.Compute.Models.SubResource()
                                {
                                    Id = p.Id
                                }
                                    ).ToList(),
                                Subnet = new ApiEntityReference()
                                {
                                    Id = subnet.Id
                                }
                            }
                        },
                        Name = string.Format("NIC-{0}-{1}", this.NodeType, start),
                        Primary = true
                    }
                }
            });
        }
 /// <summary>
 /// Creates or updates a subnet in the specified virtual network.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group.
 /// </param>
 /// <param name='virtualNetworkName'>
 /// The name of the virtual network.
 /// </param>
 /// <param name='subnetName'>
 /// The name of the subnet.
 /// </param>
 /// <param name='subnetParameters'>
 /// Parameters supplied to the create or update subnet operation.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <Subnet> BeginCreateOrUpdateAsync(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, subnetParameters, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
 /// <summary>
 /// Creates or updates a subnet in the specified virtual network.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group.
 /// </param>
 /// <param name='virtualNetworkName'>
 /// The name of the virtual network.
 /// </param>
 /// <param name='subnetName'>
 /// The name of the subnet.
 /// </param>
 /// <param name='subnetParameters'>
 /// Parameters supplied to the create or update subnet operation.
 /// </param>
 public static Subnet BeginCreateOrUpdate(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters)
 {
     return(operations.BeginCreateOrUpdateAsync(resourceGroupName, virtualNetworkName, subnetName, subnetParameters).GetAwaiter().GetResult());
 }
Пример #11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CacheHelper"/> class.
 /// </summary>
 /// <param name="subscription_id">Subscription id.</param>
 /// <param name="client">Object representing a cache management client.</param>
 /// <param name="resourceGroup">Object representing a resource group.</param>
 /// <param name="virtualNetwork">Object representing a virtual network.</param>
 /// <param name="subnet">Object representing a subnet for cache.</param>
 public CacheHelper(string subscription_id, StorageCacheManagementClient client, ResourceGroup resourceGroup, VirtualNetwork virtualNetwork, Subnet subnet)
 {
     this.StoragecacheManagementClient = client;
     this.resourceGroup  = resourceGroup;
     this.virtualNetwork = virtualNetwork;
     this.subNet         = subnet;
     this.subscriptionId = subscription_id;
 }
Пример #12
0
 /**
  * Sets the subnet.
  *
  * @param subnet the new subnet
  */
 public void setSubnet(Subnet subnet)
 {
     this.subnet = subnet;
 }
Пример #13
0
        public void UpdateSubnets(List <Wire> added, List <Wire> removed)
        {
            List <Subnet> addedSubnets   = new List <Subnet>();
            List <Subnet> deletedSubnets = new List <Subnet>();

            // FIXME: Implement equality checks and hash function for subnets or
            // don't use a hashset for this...
            HashSet <Subnet> checkSplitSubnets = new HashSet <Subnet>();

            foreach (var old in removed)
            {
                var startNet = FindSubnet(old.Pos);
                var endNet   = FindSubnet(old.EndPos);

                if (startNet != null && endNet != null)
                {
                    if (startNet == endNet)
                    {
                        // We are removing a wire from a subnet
                        // So here we want to figure out if we have to split this subnet
                        startNet.RemoveWire(old);

                        // If there are no wires left, delete this subnet
                        // otherwise we need to check if the deletion
                        // led to any splits in the subnet
                        if (startNet.Wires.Count == 0)
                        {
                            deletedSubnets.Add(startNet);
                        }
                        else
                        {
                            checkSplitSubnets.Add(startNet);
                        }
                    }
                    else
                    {
                        // This is f***ed in more ways than one...
                        Console.WriteLine($"Error! This should not happen! Trying to remove a wire containing to more than one subnet! (Wire: {old}, Subnet1: {startNet}, Subnet2:{endNet})");
                    }
                }
                else if (startNet != null)
                {
                    // We are removing from one subnet
                    if (startNet.RemoveWire(old))
                    {
                        Console.WriteLine($"Warn: Tried to remove a wire from a subnet that didn't contain that wire. (Wire: {old}, Subnet: {startNet})");
                    }

                    if (startNet.Wires.Count == 0)
                    {
                        deletedSubnets.Add(startNet);
                    }

                    Console.WriteLine($"Removed wire to subnet: {startNet}");
                }
                else if (endNet != null)
                {
                    // We are removing from one subnet
                    if (endNet.RemoveWire(old))
                    {
                        Console.WriteLine($"Warn: Tried to remove a wire from a subnet that didn't contain that wire. (Wire: {old}, Subnet: {endNet})");
                    }

                    if (endNet.Wires.Count == 0)
                    {
                        deletedSubnets.Add(endNet);
                    }

                    Console.WriteLine($"Removed wire to subnet: {endNet}");
                }
                else
                {
                    // Here we are removing a wire that didn't belong to any subnet!?
                    Console.WriteLine($"Error! This should not happen! Trying to remove a wire not contained in any subnet! (Wire: {old})");
                }
            }

            foreach (var @new in added)
            {
                var startNet = FindSubnet(@new.Pos);
                var endNet   = FindSubnet(@new.EndPos);

                if (startNet != null && endNet != null)
                {
                    if (startNet == endNet)
                    {
                        // Here they are the same subnet.
                        // So we just add the wire.
                        startNet.AddWire(@new);
                    }
                    else
                    {
                        // Here we need to merge the different subnets.
                        // FIXME: Should ID zero subnets even be allowed here?
                        // Should we check for merges later?
                        // Should we make a list?
                        Subnet merged;
                        if (startNet.ID != 0 && endNet.ID != 0)
                        {
                            Console.WriteLine($"Merging subnet ({endNet}) into subnet ({startNet}).");
                            Subnets.Remove(endNet);
                            startNet.Merge(endNet);
                            merged = startNet;
                        }
                        else if (startNet.ID != 0)
                        {
                            Console.WriteLine($"Merging subnet ({endNet}) into subnet ({startNet}).");
                            Subnets.Remove(endNet);
                            startNet.Merge(endNet);
                            merged = startNet;
                        }
                        else if (endNet.ID != 0)
                        {
                            Console.WriteLine($"Merging subnet ({startNet}) into subnet ({endNet}).");
                            Subnets.Remove(startNet);
                            endNet.Merge(startNet);
                            merged = endNet;
                        }
                        else
                        {
                            Console.WriteLine($"Warn? We are merging two subnets that both have ID zero. Subnet1: {startNet}, Subnet2: {endNet}");
                            Subnets.Remove(endNet);
                            startNet.Merge(endNet);
                            merged = startNet;
                        }

                        // Don't forget to add the wire that merged these subnets
                        merged.AddWire(@new);

                        Console.WriteLine($"\tResult: {startNet}");
                    }
                }
                else if (startNet != null)
                {
                    // Here we just add this wire to the subnet,
                    // it's not going to change anything.
                    startNet.AddWire(@new);
                    Console.WriteLine($"Added wire to subnet: {startNet}");
                }
                else if (endNet != null)
                {
                    // Here we just add this wire to the subnet,
                    // it's not going to change anything.
                    endNet.AddWire(@new);
                    Console.WriteLine($"Added wire to subnet: {endNet}");
                }
                else
                {
                    // This means that this wire should be in it's own subnet.
                    // It might get merged into another subnet later though..
                    var sub = new Subnet(0);
                    sub.AddWire(@new);
                    addedSubnets.Add(sub);

                    // NOTE: do we want to do this?
                    Subnets.Add(sub);
                    Console.WriteLine($"Added single wire subnet: {sub}");
                }
            }

            foreach (var split in checkSplitSubnets)
            {
                // Here we need to check if this subnet
                // has to be split into multiple subnets

                if (split.ID == 0)
                {
                    Console.WriteLine($"We don't need to check for splits on this subnet because it has been removed! Subnet: {split}");
                    continue;
                }

                Console.WriteLine($"Checking subnet ({split}) for splits!");

                List <Wire> wiresLeft = new List <Wire>(split.Wires);

                bool usedSplitSubnet = false;

                bool noSplit             = false;
                var  unclaimedComponents = new List <(InstanceData, int)>(split.ComponentPorts);

                while (wiresLeft.Count > 0)
                {
Пример #14
0
        private void HandleManagedIntegrationRuntime(ManagedIntegrationRuntime integrationRuntime)
        {
            if (!string.IsNullOrWhiteSpace(Location))
            {
                if (integrationRuntime.ComputeProperties == null)
                {
                    integrationRuntime.ComputeProperties = new IntegrationRuntimeComputeProperties();
                }

                integrationRuntime.ComputeProperties.Location = Location;
            }

            if (!string.IsNullOrWhiteSpace(NodeSize))
            {
                if (integrationRuntime.ComputeProperties == null)
                {
                    integrationRuntime.ComputeProperties = new IntegrationRuntimeComputeProperties();
                }

                integrationRuntime.ComputeProperties.NodeSize = NodeSize;
            }

            if (NodeCount.HasValue)
            {
                if (integrationRuntime.ComputeProperties == null)
                {
                    integrationRuntime.ComputeProperties = new IntegrationRuntimeComputeProperties();
                }

                integrationRuntime.ComputeProperties.NumberOfNodes = NodeCount;
            }

            if (MaxParallelExecutionsPerNode.HasValue)
            {
                if (integrationRuntime.ComputeProperties == null)
                {
                    integrationRuntime.ComputeProperties = new IntegrationRuntimeComputeProperties();
                }

                integrationRuntime.ComputeProperties.MaxParallelExecutionsPerNode = MaxParallelExecutionsPerNode;
            }

            if (!string.IsNullOrWhiteSpace(CatalogServerEndpoint))
            {
                if (integrationRuntime.SsisProperties == null)
                {
                    integrationRuntime.SsisProperties = new IntegrationRuntimeSsisProperties()
                    {
                        CatalogInfo = new IntegrationRuntimeSsisCatalogInfo()
                    };
                }
                else if (integrationRuntime.SsisProperties.CatalogInfo == null)
                {
                    integrationRuntime.SsisProperties.CatalogInfo = new IntegrationRuntimeSsisCatalogInfo();
                }

                integrationRuntime.SsisProperties.CatalogInfo.CatalogServerEndpoint = CatalogServerEndpoint;
            }

            if (CatalogAdminCredential != null)
            {
                if (integrationRuntime.SsisProperties == null)
                {
                    integrationRuntime.SsisProperties = new IntegrationRuntimeSsisProperties()
                    {
                        CatalogInfo = new IntegrationRuntimeSsisCatalogInfo()
                    };
                }
                else if (integrationRuntime.SsisProperties.CatalogInfo == null)
                {
                    integrationRuntime.SsisProperties.CatalogInfo = new IntegrationRuntimeSsisCatalogInfo();
                }

                integrationRuntime.SsisProperties.CatalogInfo.CatalogAdminUserName = CatalogAdminCredential.UserName;
                var passWord = ConvertToUnsecureString(CatalogAdminCredential.Password);
                if (passWord != null && passWord.Length > 128)
                {
                    throw new PSArgumentException("The password exceeds maximum length of '128'", "CatalogAdminCredential");
                }
                integrationRuntime.SsisProperties.CatalogInfo.CatalogAdminPassword = new SecureString(passWord);
            }

            if (!string.IsNullOrWhiteSpace(CatalogPricingTier))
            {
                if (integrationRuntime.SsisProperties == null)
                {
                    integrationRuntime.SsisProperties = new IntegrationRuntimeSsisProperties()
                    {
                        CatalogInfo = new IntegrationRuntimeSsisCatalogInfo()
                    };
                }
                else if (integrationRuntime.SsisProperties.CatalogInfo == null)
                {
                    integrationRuntime.SsisProperties.CatalogInfo = new IntegrationRuntimeSsisCatalogInfo();
                }

                integrationRuntime.SsisProperties.CatalogInfo.CatalogPricingTier = CatalogPricingTier;
            }

            if (integrationRuntime.ComputeProperties?.VNetProperties == null ||
                (string.IsNullOrWhiteSpace(integrationRuntime.ComputeProperties.VNetProperties.VNetId) &&
                 string.IsNullOrWhiteSpace(integrationRuntime.ComputeProperties.VNetProperties.Subnet)))
            {
                // When no previous VNet set, both VNetId and Subnet must be present
                if (!string.IsNullOrWhiteSpace(VNetId) && !string.IsNullOrWhiteSpace(Subnet))
                {
                    // Both VNetId and Subnet are set
                    if (integrationRuntime.ComputeProperties == null)
                    {
                        integrationRuntime.ComputeProperties = new IntegrationRuntimeComputeProperties();
                    }

                    integrationRuntime.ComputeProperties.VNetProperties = new IntegrationRuntimeVNetProperties()
                    {
                        VNetId = VNetId,
                        Subnet = Subnet
                    };
                }
                else if (string.IsNullOrWhiteSpace(VNetId) ^ string.IsNullOrWhiteSpace(Subnet))
                {
                    // Only one of the two pramaters is set
                    throw new PSArgumentException(string.Format(
                                                      CultureInfo.InvariantCulture,
                                                      Resources.IntegrationRuntimeInvalidVnet),
                                                  "Type");
                }
            }
            else
            {
                // We have VNet properties set, then we are able to change VNetId or Subnet individually now.
                // Could be empty. If user input empty, then convert it to null. If user want to remove VNet settings, input both with empty string.
                if (VNetId != null)
                {
                    integrationRuntime.ComputeProperties.VNetProperties.VNetId = VNetId.IsEmptyOrWhiteSpace() ? null : VNetId;
                }
                if (Subnet != null)
                {
                    integrationRuntime.ComputeProperties.VNetProperties.Subnet = Subnet.IsEmptyOrWhiteSpace() ? null : Subnet;
                }

                // Make sure both VNetId and Subnet are present, or both null
                if (string.IsNullOrWhiteSpace(integrationRuntime.ComputeProperties.VNetProperties.VNetId)
                    ^ string.IsNullOrWhiteSpace(integrationRuntime.ComputeProperties.VNetProperties.Subnet))
                {
                    throw new PSArgumentException(string.Format(
                                                      CultureInfo.InvariantCulture,
                                                      Resources.IntegrationRuntimeInvalidVnet),
                                                  "Type");
                }
            }

            if (!string.IsNullOrWhiteSpace(LicenseType))
            {
                if (integrationRuntime.SsisProperties == null)
                {
                    integrationRuntime.SsisProperties = new IntegrationRuntimeSsisProperties();
                }

                integrationRuntime.SsisProperties.LicenseType = LicenseType;
            }

            if (!string.IsNullOrEmpty(SetupScriptContainerSasUri))
            {
                if (integrationRuntime.SsisProperties == null)
                {
                    integrationRuntime.SsisProperties = new IntegrationRuntimeSsisProperties();
                }

                int index = SetupScriptContainerSasUri.IndexOf('?');

                integrationRuntime.SsisProperties.CustomSetupScriptProperties = new IntegrationRuntimeCustomSetupScriptProperties()
                {
                    BlobContainerUri = index >= 0 ? SetupScriptContainerSasUri.Substring(0, index) : SetupScriptContainerSasUri,
                    SasToken         = index >= 0 ? new SecureString(SetupScriptContainerSasUri.Substring(index)) : null
                };
            }

            if (!string.IsNullOrEmpty(Edition))
            {
                if (integrationRuntime.SsisProperties == null)
                {
                    integrationRuntime.SsisProperties = new IntegrationRuntimeSsisProperties();
                }

                integrationRuntime.SsisProperties.Edition = Edition;
            }

            integrationRuntime.Validate();
        }
Пример #15
0
        static async Task MainDatabase(string[] args)
        {
            string compartmentId = Environment.GetEnvironmentVariable("OCI_COMPARTMENT_ID");
            string adminPassword = Environment.GetEnvironmentVariable("PASSWORD");

            logger.Info("Starting example");
            // Accepts profile name and creates a auth provider based on config file
            var provider = new ConfigFileAuthenticationDetailsProvider(OciConfigProfileName);

            var identityClient       = new IdentityClient(provider);
            var virtualNetworkClient = new VirtualNetworkClient(provider);
            var databaseClient       = new DatabaseClient(provider);
            var networkCidrBlock     = "10.0.1.0/24";

            Vcn    vcn        = null;
            Subnet subnet     = null;
            string dbSystemId = null;

            AvailabilityDomain availablityDomain = await getAvailabilityDomains(identityClient, compartmentId);

            logger.Info($"availability domain is {availablityDomain.Name}");

            try
            {
                vcn = await createVcn(virtualNetworkClient, compartmentId, networkCidrBlock);

                subnet = await createSubnet(virtualNetworkClient, compartmentId, availablityDomain, networkCidrBlock, vcn);

                logger.Info("Launching Database....");

                LaunchDbSystemDetails launchDbSystemDetails = new LaunchDbSystemDetails
                {
                    AvailabilityDomain = availablityDomain.Name,
                    CompartmentId      = compartmentId,
                    CpuCoreCount       = 4,
                    Shape         = "BM.DenseIO2.52",
                    SshPublicKeys = new List <string> {
                        "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAyyA8wePstPC69PeuHFtOwyTecByonsHFAjHbVnZ+h0dpomvLZxUtbknNj3+c7MPYKqKBOx9gUKV/diR/mIDqsb405MlrI1kmNR9zbFGYAAwIH/Gxt0Lv5ffwaqsz7cECHBbMojQGEz3IH3twEvDfF6cu5p00QfP0MSmEi/eB+W+h30NGdqLJCziLDlp409jAfXbQm/4Yx7apLvEmkaYSrb5f/pfvYv1FEV1tS8/J7DgdHUAWo6gyGUUSZJgsyHcuJT7v9Tf0xwiFWOWL9WsWXa9fCKqTeYnYJhHlqfinZRnT/+jkz0OZ7YmXo6j4Hyms3RCOqenIX1W6gnIn+eQIkw== This is the key's comment"
                    },
                    SubnetId        = subnet.Id,
                    DatabaseEdition = LaunchDbSystemDetails.DatabaseEditionEnum.EnterpriseEdition,
                    DisplayName     = "OCI DotNet SDK database",
                    Hostname        = "oci-dotnetsdk-host",
                    Domain          = "testdomain",
                    DbHome          = new CreateDbHomeDetails
                    {
                        DbVersion   = "12.1.0.2",
                        DisplayName = "Example DB Home",
                        Database    = new CreateDatabaseDetails
                        {
                            DbName        = "dotnetdb",
                            AdminPassword = adminPassword
                        }
                    }
                };

                LaunchDbSystemRequest launchDbSystemRequest = new LaunchDbSystemRequest
                {
                    LaunchDbSystemDetails = launchDbSystemDetails
                };
                LaunchDbSystemResponse launchDbSystemResponse = await databaseClient.LaunchDbSystem(launchDbSystemRequest);

                logger.Info($"Database ID: {launchDbSystemResponse.DbSystem.Id} and Database display name: {launchDbSystemResponse.DbSystem.DisplayName}");
                logger.Info("Waiting for Database to come to available state....");

                GetDbSystemRequest getDbSystemRequest = new GetDbSystemRequest
                {
                    DbSystemId = launchDbSystemResponse.DbSystem.Id
                };
                WaiterConfiguration waiterConfiguration = new WaiterConfiguration
                {
                    MaxAttempts           = 20,
                    GetNextDelayInSeconds = DelayStrategy.GetExponentialDelayInSeconds
                };
                GetDbSystemResponse getDbSystemResponse = databaseClient.Waiters.ForDbSystem(
                    getDbSystemRequest, waiterConfiguration, DbSystem.LifecycleStateEnum.Available).Execute();

                logger.Info("Database is available");
                logger.Info($"Database ID: {getDbSystemResponse.DbSystem.Id} and Database display name: {getDbSystemResponse.DbSystem.DisplayName}");
                dbSystemId = getDbSystemResponse.DbSystem.Id;
            }
            catch (Exception e)
            {
                logger.Error($"failed to launch DbSystem: {e}");
            }
            finally
            {
                if (dbSystemId != null)
                {
                    await terminateDbSystem(databaseClient, dbSystemId);
                }

                if (subnet != null)
                {
                    await deleteSubnet(virtualNetworkClient, subnet);
                }

                if (vcn != null)
                {
                    await deleteVcn(virtualNetworkClient, vcn);
                }

                identityClient.Dispose();
                virtualNetworkClient.Dispose();
                databaseClient.Dispose();

                logger.Info("End example");
            }
        }
Пример #16
0
        private static async Task deleteSubnet(VirtualNetworkClient virtualNetworkClient, Subnet subnet)
        {
            DeleteSubnetRequest deleteSubnetRequest = new DeleteSubnetRequest
            {
                SubnetId = subnet.Id
            };
            await virtualNetworkClient.DeleteSubnet(deleteSubnetRequest);

            logger.Info($"Deleted Subnet: {subnet.Id}");
        }
Пример #17
0
        public async Task SubnetApiTest()
        {
            string resourceGroupName = Recording.GenerateAssetName("csmrg");

            string location = await NetworkManagementTestUtilities.GetResourceLocation(ResourceManagementClient, "Microsoft.Network/virtualNetworks");

            await ResourceGroupsOperations.CreateOrUpdateAsync(resourceGroupName, new ResourceGroup(location));

            string vnetName    = Recording.GenerateAssetName("azsmnet");
            string subnet1Name = Recording.GenerateAssetName("azsmnet");
            string subnet2Name = Recording.GenerateAssetName("azsmnet");

            VirtualNetwork vnet = new VirtualNetwork()
            {
                Location     = location,
                AddressSpace = new AddressSpace()
                {
                    AddressPrefixes = new List <string>()
                    {
                        "10.0.0.0/16",
                    }
                },
                DhcpOptions = new DhcpOptions()
                {
                    DnsServers = new List <string>()
                    {
                        "10.1.1.1", "10.1.2.4"
                    }
                },
                Subnets = new List <Subnet>()
                {
                    new Subnet()
                    {
                        Name = subnet1Name, AddressPrefix = "10.0.0.0/24",
                    }
                }
            };

            VirtualNetworksCreateOrUpdateOperation putVnetResponseOperation = await NetworkManagementClient.VirtualNetworks.StartCreateOrUpdateAsync(resourceGroupName, vnetName, vnet);

            await WaitForCompletionAsync(putVnetResponseOperation);

            // Create a Subnet
            // Populate paramters for a Subnet
            Subnet subnet = new Subnet()
            {
                Name          = subnet2Name,
                AddressPrefix = "10.0.1.0/24",
            };

            #region Verification
            SubnetsCreateOrUpdateOperation putSubnetResponseOperation = await NetworkManagementClient.Subnets.StartCreateOrUpdateAsync(resourceGroupName, vnetName, subnet2Name, subnet);
            await WaitForCompletionAsync(putSubnetResponseOperation);

            Response <VirtualNetwork> getVnetResponse = await NetworkManagementClient.VirtualNetworks.GetAsync(resourceGroupName, vnetName);

            Assert.AreEqual(2, getVnetResponse.Value.Subnets.Count());

            Response <Subnet> getSubnetResponse = await NetworkManagementClient.Subnets.GetAsync(resourceGroupName, vnetName, subnet2Name);

            // Verify the getSubnetResponse
            Assert.True(AreSubnetsEqual(getVnetResponse.Value.Subnets[1], getSubnetResponse));

            AsyncPageable <Subnet> getSubnetListResponseAP = NetworkManagementClient.Subnets.ListAsync(resourceGroupName, vnetName);
            List <Subnet>          getSubnetListResponse   = await getSubnetListResponseAP.ToEnumerableAsync();

            // Verify ListSubnets
            Assert.True(AreSubnetsEqual(getVnetResponse.Value.Subnets, getSubnetListResponse));

            // Delete the subnet "subnet1"
            await NetworkManagementClient.Subnets.StartDeleteAsync(resourceGroupName, vnetName, subnet2Name);

            // Verify that the deletion was successful
            getSubnetListResponseAP = NetworkManagementClient.Subnets.ListAsync(resourceGroupName, vnetName);
            getSubnetListResponse   = await getSubnetListResponseAP.ToEnumerableAsync();

            Has.One.EqualTo(getSubnetListResponse);
            Assert.AreEqual(subnet1Name, getSubnetListResponse.ElementAt(0).Name);
            #endregion
        }
        public void TestVirtualMachineNicConfiguration()
        {
            string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION");

            using (MockContext context = MockContext.Start(this.GetType()))
            {
                // Hard code the location to "eastus2euap".
                // This is because NRP is still deploying to other regions and is not available worldwide.
                // Before changing the default location, we have to save it to be reset it at the end of the test.
                // Since ComputeManagementTestUtilities.DefaultLocation is a static variable and can affect other tests if it is not reset.
                Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus2euap");
                EnsureClientsInitialized(context);

                ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true);

                string rgName = ComputeManagementTestUtilities.GenerateName(TestPrefix);
                //string asName = ComputeManagementTestUtilities.GenerateName("as");
                string         storageAccountName = ComputeManagementTestUtilities.GenerateName(TestPrefix);
                VirtualMachine inputVM;
                try
                {
                    // Create the resource Group, it might have been already created during StorageAccount creation.
                    var resourceGroup = m_ResourcesClient.ResourceGroups.CreateOrUpdate(
                        rgName,
                        new ResourceGroup
                    {
                        Location = m_location,
                        Tags     = new Dictionary <string, string>()
                        {
                            { rgName, DateTime.UtcNow.ToString("u") }
                        }
                    });

                    // Create Storage Account, so that both the VMs can share it
                    var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName);

                    Subnet subnetResponse = CreateVNET(rgName);

                    VirtualMachineNetworkInterfaceConfiguration vmNicConfig = CreateNICConfig(subnetResponse);

                    //string asetId = CreateAvailabilitySet(rgName, asName);

                    inputVM = CreateDefaultVMInput(rgName, storageAccountName, imageRef, asetId: null, vmNicConfig: vmNicConfig, networkApiVersion: NetworkApiVersion.TwoZeroTwoZeroHyphenMinusOneOneHyphenMinusZeroOne);

                    string expectedVMReferenceId = Helpers.GetVMReferenceId(m_subId, rgName, inputVM.Name);

                    var createOrUpdateResponse = m_CrpClient.VirtualMachines.CreateOrUpdate(
                        rgName, inputVM.Name, inputVM);

                    Assert.NotNull(createOrUpdateResponse);

                    var getVMResponse = m_CrpClient.VirtualMachines.Get(rgName, inputVM.Name);

                    ValidateVM(inputVM, getVMResponse, expectedVMReferenceId, hasUserDefinedAS: false);

                    var getNicResponse = m_NrpClient.NetworkInterfaces.List(rgName);
                    // TODO AutoRest: Recording Passed, but these assertions failed in Playback mode
                    Assert.NotNull(getNicResponse.FirstOrDefault().MacAddress);
                    Assert.NotNull(getNicResponse.FirstOrDefault().Primary);
                    Assert.True(getNicResponse.FirstOrDefault().Primary != null && getNicResponse.FirstOrDefault().Primary.Value);
                }
                finally
                {
                    Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
                    // Cleanup the created resources
                    m_ResourcesClient.ResourceGroups.Delete(rgName);
                }
            }
        }
Пример #19
0
        public override string ToString()
        {
            var sb = new StringBuilder();

            sb.AppendFormat("   System Ids:").AppendLine();
            sb.AppendFormat("      ServiceId: {0}", ServiceId).AppendLine();
            sb.AppendFormat("      DeploymentId: {0}", DeploymentId).AppendLine();
            sb.Append("   Subnet: ").Append(Subnet == null ? "" : Subnet.ToStrings(x => x.ToString(CultureInfo.InvariantCulture), ".")).AppendLine();
            sb.Append("   Seed nodes: ");
            bool first = true;

            foreach (IPEndPoint node in SeedNodes)
            {
                if (!first)
                {
                    sb.Append(", ");
                }
                sb.Append(node.ToString());
                first = false;
            }
            sb.AppendLine();
            sb.AppendFormat(base.ToString());
            sb.AppendFormat("   Liveness:").AppendLine();
            sb.AppendFormat("      LivenessEnabled: {0}", LivenessEnabled).AppendLine();
            sb.AppendFormat("      LivenessType: {0}", LivenessType).AppendLine();
            sb.AppendFormat("      ProbeTimeout: {0}", ProbeTimeout).AppendLine();
            sb.AppendFormat("      TableRefreshTimeout: {0}", TableRefreshTimeout).AppendLine();
            sb.AppendFormat("      DeathVoteExpirationTimeout: {0}", DeathVoteExpirationTimeout).AppendLine();
            sb.AppendFormat("      NumMissedProbesLimit: {0}", NumMissedProbesLimit).AppendLine();
            sb.AppendFormat("      NumProbedSilos: {0}", NumProbedSilos).AppendLine();
            sb.AppendFormat("      NumVotesForDeathDeclaration: {0}", NumVotesForDeathDeclaration).AppendLine();
            sb.AppendFormat("      UseLivenessGossip: {0}", UseLivenessGossip).AppendLine();
            sb.AppendFormat("      IAmAliveTablePublishTimeout: {0}", IAmAliveTablePublishTimeout).AppendLine();
            sb.AppendFormat("      NumMissedTableIAmAliveLimit: {0}", NumMissedTableIAmAliveLimit).AppendLine();
            sb.AppendFormat("      MaxJoinAttemptTime: {0}", MaxJoinAttemptTime).AppendLine();
            sb.AppendFormat("      ExpectedClusterSize: {0}", ExpectedClusterSize).AppendLine();
            sb.AppendFormat("   SystemStore:").AppendLine();
            // Don't print connection credentials in log files, so pass it through redactment filter
            string connectionStringForLog = ConfigUtilities.RedactConnectionStringInfo(DataConnectionString);

            sb.AppendFormat("      ConnectionString: {0}", connectionStringForLog).AppendLine();
            sb.Append(Application.ToString()).AppendLine();
            sb.Append("   PlacementStrategy: ").AppendLine();
            sb.Append("      ").Append("   Default Placement Strategy: ").Append(DefaultPlacementStrategy).AppendLine();
            sb.Append("      ").Append("   Deployment Load Publisher Refresh Time: ").Append(DeploymentLoadPublisherRefreshTime).AppendLine();
            sb.Append("      ").Append("   Activation CountBased Placement Choose Out Of: ").Append(ActivationCountBasedPlacementChooseOutOf).AppendLine();
            sb.AppendFormat("   Grain directory cache:").AppendLine();
            sb.AppendFormat("      Maximum size: {0} grains", CacheSize).AppendLine();
            sb.AppendFormat("      Initial TTL: {0}", InitialCacheTTL).AppendLine();
            sb.AppendFormat("      Maximum TTL: {0}", MaximumCacheTTL).AppendLine();
            sb.AppendFormat("      TTL extension factor: {0:F2}", CacheTTLExtensionFactor).AppendLine();
            sb.AppendFormat("      Directory Caching Strategy: {0}", DirectoryCachingStrategy).AppendLine();
            sb.AppendFormat("   Grain directory:").AppendLine();
            sb.AppendFormat("      Lazy deregistration delay: {0}", DirectoryLazyDeregistrationDelay).AppendLine();
            sb.AppendFormat("      Client registration refresh: {0}", ClientRegistrationRefresh).AppendLine();
            sb.AppendFormat("   Reminder Service:").AppendLine();
            sb.AppendFormat("       ReminderServiceType: {0}", ReminderServiceType).AppendLine();
            if (ReminderServiceType == ReminderServiceProviderType.MockTable)
            {
                sb.AppendFormat("       MockReminderTableTimeout: {0}ms", MockReminderTableTimeout.TotalMilliseconds).AppendLine();
            }
            sb.AppendFormat("   Consistent Ring:").AppendLine();
            sb.AppendFormat("       Use Virtual Buckets Consistent Ring: {0}", UseVirtualBucketsConsistentRing).AppendLine();
            sb.AppendFormat("       Num Virtual Buckets Consistent Ring: {0}", NumVirtualBucketsConsistentRing).AppendLine();
            sb.AppendFormat("   Providers:").AppendLine();
            sb.Append(ProviderConfigurationUtility.PrintProviderConfigurations(ProviderConfigurations));

            return(sb.ToString());
        }
Пример #20
0
        public static IEnumerable <Subnet> FewestConsecutiveSubnetsFor([NotNull] IPAddress left,
                                                                       [NotNull] IPAddress right)
        {
            #region defense

            if (left == null)
            {
                throw new ArgumentNullException(nameof(left));
            }

            if (right == null)
            {
                throw new ArgumentNullException(nameof(right));
            }

            if (!IPAddressUtilities.ValidAddressFamilies.Contains(left.AddressFamily))
            {
                throw new ArgumentException($"{nameof(left)} must have an address family equal to {string.Join(", ", IPAddressUtilities.ValidAddressFamilies)}", nameof(left));
            }

            if (!IPAddressUtilities.ValidAddressFamilies.Contains(right.AddressFamily))
            {
                throw new ArgumentException($"{nameof(right)} must have an address family equal to {string.Join(", ", IPAddressUtilities.ValidAddressFamilies)}", nameof(right));
            }

            if (left.AddressFamily != right.AddressFamily)
            {
                throw new InvalidOperationException($"{nameof(left)} and {nameof(right)} must have matching address families");
            }

            #endregion // end: defense

            var minHead = IPAddressMath.Min(left, right);
            var maxTail = IPAddressMath.Max(left, right);

            return(FilledSubnets(minHead, maxTail, new Subnet(minHead, maxTail)));

            // recursive function call
            // Works by verifying that passed subnet isn't bounded by head, tail IP Addresses
            // if not breaks subnet in half and recursively tests, building in essence a binary tree of testable subnet paths
            IEnumerable <Subnet> FilledSubnets(IPAddress head,
                                               IPAddress tail,
                                               Subnet subnet)
            {
                var networkPrefixAddress = subnet.NetworkPrefixAddress;
                var broadcastAddress     = subnet.BroadcastAddress;

                // the given subnet is the perfect size for the head/tail (not papa bear, not mama bear, but just right with baby bear)
                if (networkPrefixAddress.IsGreaterThanOrEqualTo(head) &&
                    broadcastAddress.IsLessThanOrEqualTo(tail))
                {
                    return(new[] { subnet });
                }

                // increasing the route prefix by 1 creates a subnet of half the initial size (due 2^(max-n) route prefix sizing)
                var nextSmallestRoutePrefix = subnet.RoutingPrefix + 1;

                // over-iterated route prefix, no valid subnet beyond this point; end search on this branch
                if ((subnet.IsIPv6 && nextSmallestRoutePrefix > IPAddressUtilities.IPv6BitCount) ||
                    (subnet.IsIPv4 && nextSmallestRoutePrefix > IPAddressUtilities.IPv4BitCount))
                {
                    return(Enumerable.Empty <Subnet>()); // no subnets to be found here, stop investigating branch of tree
                }

                // build head subnet
                var headSubnet = new Subnet(networkPrefixAddress, nextSmallestRoutePrefix);

                // use the next address after the end of the head subnet as the first address for the tail subnet
                if (!IPAddressMath.TryIncrement(headSubnet.BroadcastAddress, out var tailStartingAddress))
                {
                    throw new InvalidOperationException($"unable to increment {headSubnet.BroadcastAddress}");
                }

                // ReSharper disable once AssignNullToNotNullAttribute
                var tailSubnet = new Subnet(tailStartingAddress, nextSmallestRoutePrefix);

                // break into binary search tree, searching both head subnet and tail subnet for ownership of head and tail ip
                return(FilledSubnets(head, tail, headSubnet)
                       .Concat(FilledSubnets(head, tail, tailSubnet)));
            }
        }
Пример #21
0
        private ApplicationGateway CreateApplicationGateway(string location, Subnet subnet, string resourceGroupName, string subscriptionId)
        {
            var appGwName               = TestUtilities.GenerateName();
            var gatewayIPConfigName     = TestUtilities.GenerateName();
            var frontendIPConfigName    = TestUtilities.GenerateName();
            var frontendPortName        = TestUtilities.GenerateName();
            var backendAddressPoolName  = TestUtilities.GenerateName();
            var backendHttpSettingsName = TestUtilities.GenerateName();
            var requestRoutingRuleName  = TestUtilities.GenerateName();
            var httpListenerName        = TestUtilities.GenerateName();

            var appGw = new ApplicationGateway()
            {
                Location = location,
                Name     = appGwName,
                Sku      = new ApplicationGatewaySku()
                {
                    Name     = ApplicationGatewaySkuName.StandardSmall,
                    Tier     = ApplicationGatewayTier.Standard,
                    Capacity = 2
                },
                GatewayIPConfigurations = new List <ApplicationGatewayIPConfiguration>()
                {
                    new ApplicationGatewayIPConfiguration()
                    {
                        Name   = gatewayIPConfigName,
                        Subnet = new ResourceId()
                        {
                            Id = subnet.Id
                        }
                    }
                },
                FrontendIPConfigurations = new List <ApplicationGatewayFrontendIPConfiguration>()
                {
                    new ApplicationGatewayFrontendIPConfiguration()
                    {
                        Name = frontendIPConfigName,
                        PrivateIPAllocationMethod = IpAllocationMethod.Dynamic,
                        Subnet = new ResourceId()
                        {
                            Id = subnet.Id
                        }
                    }
                },
                FrontendPorts = new List <ApplicationGatewayFrontendPort>
                {
                    new ApplicationGatewayFrontendPort()
                    {
                        Name = frontendPortName,
                        Port = 80
                    }
                },
                BackendAddressPools = new List <ApplicationGatewayBackendAddressPool>
                {
                    new ApplicationGatewayBackendAddressPool()
                    {
                        Name             = backendAddressPoolName,
                        BackendAddresses = new List <ApplicationGatewayBackendAddress>()
                        {
                            new ApplicationGatewayBackendAddress()
                            {
                                IpAddress = "104.42.6.202"
                            },
                            new ApplicationGatewayBackendAddress()
                            {
                                IpAddress = "23.99.1.115"
                            }
                        }
                    }
                },
                BackendHttpSettingsCollection = new List <ApplicationGatewayBackendHttpSettings>
                {
                    new ApplicationGatewayBackendHttpSettings()
                    {
                        Name                = backendHttpSettingsName,
                        Port                = 80,
                        Protocol            = ApplicationGatewayProtocol.Http,
                        CookieBasedAffinity = ApplicationGatewayCookieBasedAffinity.Disabled
                    }
                },
                HttpListeners = new List <ApplicationGatewayHttpListener>
                {
                    new ApplicationGatewayHttpListener()
                    {
                        Name         = httpListenerName,
                        FrontendPort = new ResourceId()
                        {
                            Id = GetChildAppGwResourceId(subscriptionId,
                                                         resourceGroupName, appGwName, "frontendPorts", frontendPortName)
                        },
                        FrontendIPConfiguration = new ResourceId()
                        {
                            Id = GetChildAppGwResourceId(subscriptionId,
                                                         resourceGroupName, appGwName, "frontendIPConfigurations", frontendIPConfigName)
                        },
                        SslCertificate = null,
                        Protocol       = ApplicationGatewayProtocol.Http
                    }
                },
                RequestRoutingRules = new List <ApplicationGatewayRequestRoutingRule>()
                {
                    new ApplicationGatewayRequestRoutingRule()
                    {
                        Name         = requestRoutingRuleName,
                        RuleType     = ApplicationGatewayRequestRoutingRuleType.Basic,
                        HttpListener = new ResourceId()
                        {
                            Id = GetChildAppGwResourceId(subscriptionId,
                                                         resourceGroupName, appGwName, "httpListeners", httpListenerName)
                        },
                        BackendAddressPool = new ResourceId()
                        {
                            Id = GetChildAppGwResourceId(subscriptionId,
                                                         resourceGroupName, appGwName, "backendAddressPools", backendAddressPoolName)
                        },
                        BackendHttpSettings = new ResourceId()
                        {
                            Id = GetChildAppGwResourceId(subscriptionId,
                                                         resourceGroupName, appGwName, "backendHttpSettingsCollection", backendHttpSettingsName)
                        }
                    }
                }
            };

            return(appGw);
        }
Пример #22
0
 internal IPConfigurationProfile(string id, string name, string type, string etag, Subnet subnet, ProvisioningState?provisioningState) : base(id)
 {
     Name              = name;
     Type              = type;
     Etag              = etag;
     Subnet            = subnet;
     ProvisioningState = provisioningState;
 }
        private VirtualMachineScaleSet CreateVMScaleSetAndGetOperationResponse(
            string rgName,
            string vmssName,
            StorageAccount storageAccount,
            ImageReference imageRef,
            out VirtualMachineScaleSet inputVMScaleSet,
            VirtualMachineScaleSetExtensionProfile extensionProfile = null,
            Action <VirtualMachineScaleSet> vmScaleSetCustomizer    = null,
            bool createWithPublicIpAddress = false,
            bool createWithManagedDisks    = false,
            bool hasDiffDisks          = false,
            bool createWithHealthProbe = false,
            Subnet subnet              = null,
            IList <string> zones       = null,
            int?osDiskSizeInGB         = null,
            string ppgId               = null,
            string machineSizeType     = null,
            bool?enableUltraSSD        = false,
            string diskEncryptionSetId = null,
            AutomaticRepairsPolicy automaticRepairsPolicy = null,
            bool?encryptionAtHostEnabled = null,
            bool singlePlacementGroup    = true,
            DiagnosticsProfile bootDiagnosticsProfile = null,
            int?faultDomainCount = null,
            int?capacity         = null,
            string dedicatedHostGroupReferenceId = null,
            string dedicatedHostGroupName        = null,
            string dedicatedHostName             = null)
        {
            // Create the resource Group, it might have been already created during StorageAccount creation.
            var resourceGroup = m_ResourcesClient.ResourceGroups.CreateOrUpdate(
                rgName,
                new ResourceGroup
            {
                Location = m_location
            });

            var getPublicIpAddressResponse = createWithPublicIpAddress ? null : CreatePublicIP(rgName);

            var subnetResponse = subnet ?? CreateVNET(rgName);

            var nicResponse = CreateNIC(
                rgName,
                subnetResponse,
                getPublicIpAddressResponse != null ? getPublicIpAddressResponse.IpAddress : null);

            var loadBalancer = (getPublicIpAddressResponse != null && createWithHealthProbe) ?
                               CreatePublicLoadBalancerWithProbe(rgName, getPublicIpAddressResponse) : null;

            Assert.True(createWithManagedDisks || storageAccount != null);
            inputVMScaleSet = CreateDefaultVMScaleSetInput(rgName, storageAccount?.Name, imageRef, subnetResponse.Id, hasManagedDisks: createWithManagedDisks,
                                                           healthProbeId: loadBalancer?.Probes?.FirstOrDefault()?.Id,
                                                           loadBalancerBackendPoolId: loadBalancer?.BackendAddressPools?.FirstOrDefault()?.Id, zones: zones, osDiskSizeInGB: osDiskSizeInGB,
                                                           machineSizeType: machineSizeType, enableUltraSSD: enableUltraSSD, diskEncryptionSetId: diskEncryptionSetId, automaticRepairsPolicy: automaticRepairsPolicy,
                                                           bootDiagnosticsProfile: bootDiagnosticsProfile, faultDomainCount: faultDomainCount, capacity: capacity);
            if (vmScaleSetCustomizer != null)
            {
                vmScaleSetCustomizer(inputVMScaleSet);
            }

            if (encryptionAtHostEnabled != null)
            {
                inputVMScaleSet.VirtualMachineProfile.SecurityProfile = new SecurityProfile
                {
                    EncryptionAtHost = encryptionAtHostEnabled.Value
                };
            }

            if (hasDiffDisks)
            {
                VirtualMachineScaleSetOSDisk osDisk = new VirtualMachineScaleSetOSDisk();
                osDisk.Caching          = CachingTypes.ReadOnly;
                osDisk.CreateOption     = DiskCreateOptionTypes.FromImage;
                osDisk.DiffDiskSettings = new DiffDiskSettings {
                    Option    = DiffDiskOptions.Local,
                    Placement = DiffDiskPlacement.CacheDisk
                };
                inputVMScaleSet.VirtualMachineProfile.StorageProfile.OsDisk = osDisk;
            }

            inputVMScaleSet.VirtualMachineProfile.ExtensionProfile = extensionProfile;

            if (ppgId != null)
            {
                inputVMScaleSet.ProximityPlacementGroup = new Microsoft.Azure.Management.Compute.Models.SubResource()
                {
                    Id = ppgId
                };
            }

            if (dedicatedHostGroupReferenceId != null)
            {
                CreateDedicatedHostGroup(rgName, dedicatedHostGroupName, availabilityZone: null);
                CreateDedicatedHost(rgName, dedicatedHostGroupName, dedicatedHostName, "DSv3-Type1");
                inputVMScaleSet.HostGroup = new CM.SubResource()
                {
                    Id = dedicatedHostGroupReferenceId
                };
            }

            inputVMScaleSet.SinglePlacementGroup = singlePlacementGroup ? (bool?)null : false;

            VirtualMachineScaleSet createOrUpdateResponse = null;

            try
            {
                createOrUpdateResponse = m_CrpClient.VirtualMachineScaleSets.CreateOrUpdate(rgName, vmssName, inputVMScaleSet);

                Assert.True(createOrUpdateResponse.Name == vmssName);
                Assert.True(createOrUpdateResponse.Location.ToLower() == inputVMScaleSet.Location.ToLower().Replace(" ", ""));
            }
            catch (CloudException e)
            {
                if (e.Message.Contains("the allotted time"))
                {
                    createOrUpdateResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName);
                }
                else
                {
                    throw;
                }
            }

            ValidateVMScaleSet(inputVMScaleSet, createOrUpdateResponse, createWithManagedDisks, ppgId: ppgId, dedicatedHostGroupReferenceId: dedicatedHostGroupReferenceId);

            return(createOrUpdateResponse);
        }
Пример #24
0
        private ApplicationGateway CreateApplicationGateway(string location, Subnet subnet, string resourceGroupName, string appGwName, string subscriptionId)
        {
            var gatewayIPConfigName       = TestUtilities.GenerateName();
            var frontendIPConfigName      = TestUtilities.GenerateName();
            var frontendPort1Name         = TestUtilities.GenerateName();
            var frontendPort2Name         = TestUtilities.GenerateName();
            var frontendPort3Name         = TestUtilities.GenerateName();
            var frontendPort4Name         = TestUtilities.GenerateName();
            var backendAddressPoolName    = TestUtilities.GenerateName();
            var nicBackendAddressPoolName = TestUtilities.GenerateName();
            var backendHttpSettings1Name  = TestUtilities.GenerateName();
            var backendHttpSettings2Name  = TestUtilities.GenerateName();
            var requestRoutingRule1Name   = TestUtilities.GenerateName();
            var requestRoutingRule2Name   = TestUtilities.GenerateName();
            var requestRoutingRule3Name   = TestUtilities.GenerateName();
            var requestRoutingRule4Name   = TestUtilities.GenerateName();
            var httpListener1Name         = TestUtilities.GenerateName();
            var httpListener2Name         = TestUtilities.GenerateName();
            var httpListener3Name         = TestUtilities.GenerateName();
            var httpListener4Name         = TestUtilities.GenerateName();
            var probeName    = TestUtilities.GenerateName();
            var sslCertName  = TestUtilities.GenerateName();
            var authCertName = TestUtilities.GenerateName();
            var redirectConfiguration1Name = TestUtilities.GenerateName();
            var redirectConfiguration2Name = TestUtilities.GenerateName();
            var urlPathMapName             = TestUtilities.GenerateName();
            var pathRuleName = TestUtilities.GenerateName();

            var appGw = new ApplicationGateway()
            {
                Location = location,
                Sku      = new ApplicationGatewaySku()
                {
                    Name     = ApplicationGatewaySkuName.WAFMedium,
                    Tier     = ApplicationGatewayTier.WAF,
                    Capacity = 2
                },
                GatewayIPConfigurations = new List <ApplicationGatewayIPConfiguration>()
                {
                    new ApplicationGatewayIPConfiguration()
                    {
                        Name   = gatewayIPConfigName,
                        Subnet = new SubResource()
                        {
                            Id = subnet.Id
                        }
                    }
                },
                FrontendIPConfigurations = new List <ApplicationGatewayFrontendIPConfiguration>()
                {
                    new ApplicationGatewayFrontendIPConfiguration()
                    {
                        Name = frontendIPConfigName,
                        PrivateIPAllocationMethod = IPAllocationMethod.Dynamic,
                        Subnet = new SubResource()
                        {
                            Id = subnet.Id
                        }
                    }
                },
                FrontendPorts = new List <ApplicationGatewayFrontendPort>
                {
                    new ApplicationGatewayFrontendPort()
                    {
                        Name = frontendPort1Name,
                        Port = 80
                    },
                    new ApplicationGatewayFrontendPort()
                    {
                        Name = frontendPort2Name,
                        Port = 443
                    },
                    new ApplicationGatewayFrontendPort()
                    {
                        Name = frontendPort3Name,
                        Port = 8080
                    },
                    new ApplicationGatewayFrontendPort()
                    {
                        Name = frontendPort4Name,
                        Port = 8081
                    }
                },
                Probes = new List <ApplicationGatewayProbe>
                {
                    new ApplicationGatewayProbe()
                    {
                        Name               = probeName,
                        Protocol           = ApplicationGatewayProtocol.Http,
                        Path               = "/path/path.htm",
                        Interval           = 17,
                        Timeout            = 17,
                        UnhealthyThreshold = 5,
                        PickHostNameFromBackendHttpSettings = true,
                        Match = new ApplicationGatewayProbeHealthResponseMatch
                        {
                            Body        = "helloworld",
                            StatusCodes = new List <string> {
                                "200-300", "403"
                            }
                        }
                    }
                },
                BackendAddressPools = new List <ApplicationGatewayBackendAddressPool>
                {
                    new ApplicationGatewayBackendAddressPool()
                    {
                        Name             = backendAddressPoolName,
                        BackendAddresses = new List <ApplicationGatewayBackendAddress>()
                        {
                            new ApplicationGatewayBackendAddress()
                            {
                                IpAddress = "hello1.azurewebsites.net"
                            },
                            new ApplicationGatewayBackendAddress()
                            {
                                IpAddress = "hello2.azurewebsites.net"
                            }
                        }
                    },
                    new ApplicationGatewayBackendAddressPool()
                    {
                        Name = nicBackendAddressPoolName
                    }
                },
                BackendHttpSettingsCollection = new List <ApplicationGatewayBackendHttpSettings>
                {
                    new ApplicationGatewayBackendHttpSettings()
                    {
                        Name                = backendHttpSettings1Name,
                        Port                = 80,
                        Protocol            = ApplicationGatewayProtocol.Http,
                        CookieBasedAffinity = ApplicationGatewayCookieBasedAffinity.Disabled,
                        RequestTimeout      = 69,
                        Probe               = new SubResource()
                        {
                            Id = GetChildAppGwResourceId(subscriptionId,
                                                         resourceGroupName, appGwName, "probes", probeName)
                        },
                        ConnectionDraining = new ApplicationGatewayConnectionDraining()
                        {
                            Enabled           = true,
                            DrainTimeoutInSec = 42
                        },
                        ProbeEnabled = true,
                        PickHostNameFromBackendAddress = true
                    },
                    new ApplicationGatewayBackendHttpSettings()
                    {
                        Name                       = backendHttpSettings2Name,
                        Port                       = 443,
                        Protocol                   = ApplicationGatewayProtocol.Https,
                        CookieBasedAffinity        = ApplicationGatewayCookieBasedAffinity.Enabled,
                        AuthenticationCertificates = new List <SubResource>()
                        {
                            new SubResource()
                            {
                                Id = GetChildAppGwResourceId(subscriptionId,
                                                             resourceGroupName, appGwName, "authenticationCertificates", authCertName)
                            }
                        }
                    }
                },
                HttpListeners = new List <ApplicationGatewayHttpListener>
                {
                    new ApplicationGatewayHttpListener()
                    {
                        Name         = httpListener1Name,
                        FrontendPort = new SubResource()
                        {
                            Id = GetChildAppGwResourceId(subscriptionId,
                                                         resourceGroupName, appGwName, "frontendPorts", frontendPort1Name)
                        },
                        FrontendIPConfiguration = new SubResource()
                        {
                            Id = GetChildAppGwResourceId(subscriptionId,
                                                         resourceGroupName, appGwName, "frontendIPConfigurations", frontendIPConfigName)
                        },
                        SslCertificate = null,
                        Protocol       = ApplicationGatewayProtocol.Http
                    },
                    new ApplicationGatewayHttpListener()
                    {
                        Name         = httpListener2Name,
                        FrontendPort = new SubResource()
                        {
                            Id = GetChildAppGwResourceId(subscriptionId,
                                                         resourceGroupName, appGwName, "frontendPorts", frontendPort2Name)
                        },
                        FrontendIPConfiguration = new SubResource()
                        {
                            Id = GetChildAppGwResourceId(subscriptionId,
                                                         resourceGroupName, appGwName, "frontendIPConfigurations", frontendIPConfigName)
                        },
                        SslCertificate = new SubResource()
                        {
                            Id = GetChildAppGwResourceId(subscriptionId,
                                                         resourceGroupName, appGwName, "sslCertificates", sslCertName)
                        },
                        Protocol = ApplicationGatewayProtocol.Https
                    },
                    new ApplicationGatewayHttpListener()
                    {
                        Name         = httpListener3Name,
                        FrontendPort = new SubResource()
                        {
                            Id = GetChildAppGwResourceId(subscriptionId,
                                                         resourceGroupName, appGwName, "frontendPorts", frontendPort3Name)
                        },
                        FrontendIPConfiguration = new SubResource()
                        {
                            Id = GetChildAppGwResourceId(subscriptionId,
                                                         resourceGroupName, appGwName, "frontendIPConfigurations", frontendIPConfigName)
                        },
                        SslCertificate = new SubResource()
                        {
                            Id = GetChildAppGwResourceId(subscriptionId,
                                                         resourceGroupName, appGwName, "sslCertificates", sslCertName)
                        },
                        Protocol = ApplicationGatewayProtocol.Https
                    },
                    new ApplicationGatewayHttpListener()
                    {
                        Name         = httpListener4Name,
                        FrontendPort = new SubResource()
                        {
                            Id = GetChildAppGwResourceId(subscriptionId,
                                                         resourceGroupName, appGwName, "frontendPorts", frontendPort4Name)
                        },
                        FrontendIPConfiguration = new SubResource()
                        {
                            Id = GetChildAppGwResourceId(subscriptionId,
                                                         resourceGroupName, appGwName, "frontendIPConfigurations", frontendIPConfigName)
                        },
                        SslCertificate = new SubResource()
                        {
                            Id = GetChildAppGwResourceId(subscriptionId,
                                                         resourceGroupName, appGwName, "sslCertificates", sslCertName)
                        },
                        Protocol = ApplicationGatewayProtocol.Https
                    }
                },
                UrlPathMaps = new List <ApplicationGatewayUrlPathMap>()
                {
                    new ApplicationGatewayUrlPathMap {
                        Name = urlPathMapName,
                        DefaultRedirectConfiguration = new SubResource
                        {
                            Id = GetChildAppGwResourceId(subscriptionId,
                                                         resourceGroupName, appGwName, "redirectConfigurations", redirectConfiguration2Name)
                        },
                        PathRules = new List <ApplicationGatewayPathRule>
                        {
                            new ApplicationGatewayPathRule {
                                Name  = pathRuleName,
                                Paths = new List <string> {
                                    "/paa"
                                },
                                BackendAddressPool = new SubResource()
                                {
                                    Id = GetChildAppGwResourceId(subscriptionId,
                                                                 resourceGroupName, appGwName, "backendAddressPools", backendAddressPoolName)
                                },
                                BackendHttpSettings = new SubResource()
                                {
                                    Id = GetChildAppGwResourceId(subscriptionId,
                                                                 resourceGroupName, appGwName, "backendHttpSettingsCollection", backendHttpSettings1Name)
                                }
                            }
                        }
                    }
                },
                RequestRoutingRules = new List <ApplicationGatewayRequestRoutingRule>()
                {
                    new ApplicationGatewayRequestRoutingRule()
                    {
                        Name         = requestRoutingRule1Name,
                        RuleType     = ApplicationGatewayRequestRoutingRuleType.Basic,
                        HttpListener = new SubResource()
                        {
                            Id = GetChildAppGwResourceId(subscriptionId,
                                                         resourceGroupName, appGwName, "httpListeners", httpListener1Name)
                        },
                        BackendAddressPool = new SubResource()
                        {
                            Id = GetChildAppGwResourceId(subscriptionId,
                                                         resourceGroupName, appGwName, "backendAddressPools", backendAddressPoolName)
                        },
                        BackendHttpSettings = new SubResource()
                        {
                            Id = GetChildAppGwResourceId(subscriptionId,
                                                         resourceGroupName, appGwName, "backendHttpSettingsCollection", backendHttpSettings1Name)
                        }
                    },
                    new ApplicationGatewayRequestRoutingRule()
                    {
                        Name         = requestRoutingRule2Name,
                        RuleType     = ApplicationGatewayRequestRoutingRuleType.Basic,
                        HttpListener = new SubResource()
                        {
                            Id = GetChildAppGwResourceId(subscriptionId,
                                                         resourceGroupName, appGwName, "httpListeners", httpListener2Name)
                        },
                        RedirectConfiguration = new SubResource()
                        {
                            Id = GetChildAppGwResourceId(subscriptionId,
                                                         resourceGroupName, appGwName, "redirectConfigurations", redirectConfiguration1Name)
                        }
                    },
                    new ApplicationGatewayRequestRoutingRule()
                    {
                        Name         = requestRoutingRule3Name,
                        RuleType     = ApplicationGatewayRequestRoutingRuleType.PathBasedRouting,
                        HttpListener = new SubResource()
                        {
                            Id = GetChildAppGwResourceId(subscriptionId,
                                                         resourceGroupName, appGwName, "httpListeners", httpListener3Name)
                        },
                        UrlPathMap = new SubResource()
                        {
                            Id = GetChildAppGwResourceId(subscriptionId,
                                                         resourceGroupName, appGwName, "urlPathMaps", urlPathMapName)
                        }
                    },
                    new ApplicationGatewayRequestRoutingRule()
                    {
                        Name         = requestRoutingRule4Name,
                        RuleType     = ApplicationGatewayRequestRoutingRuleType.Basic,
                        HttpListener = new SubResource()
                        {
                            Id = GetChildAppGwResourceId(subscriptionId,
                                                         resourceGroupName, appGwName, "httpListeners", httpListener4Name)
                        },
                        BackendAddressPool = new SubResource()
                        {
                            Id = GetChildAppGwResourceId(subscriptionId,
                                                         resourceGroupName, appGwName, "backendAddressPools", nicBackendAddressPoolName)
                        },
                        BackendHttpSettings = new SubResource()
                        {
                            Id = GetChildAppGwResourceId(subscriptionId,
                                                         resourceGroupName, appGwName, "backendHttpSettingsCollection", backendHttpSettings2Name)
                        }
                    },
                },
                AuthenticationCertificates          = CreateAuthCertificate(authCertName),
                WebApplicationFirewallConfiguration = new ApplicationGatewayWebApplicationFirewallConfiguration()
                {
                    Enabled            = true,
                    FirewallMode       = ApplicationGatewayFirewallMode.Prevention,
                    RuleSetType        = "OWASP",
                    RuleSetVersion     = "2.2.9",
                    DisabledRuleGroups = new List <ApplicationGatewayFirewallDisabledRuleGroup>()
                    {
                        new ApplicationGatewayFirewallDisabledRuleGroup(
                            "crs_41_sql_injection_attacks",
                            new List <int>()
                        {
                            981318, 981320
                        }),
                        new ApplicationGatewayFirewallDisabledRuleGroup("crs_35_bad_robots")
                    }
                },
                SslPolicy = new ApplicationGatewaySslPolicy()
                {
                    PolicyType = "Predefined",
                    PolicyName = "AppGwSslPolicy20170401"
                },
                RedirectConfigurations = new List <ApplicationGatewayRedirectConfiguration>
                {
                    new ApplicationGatewayRedirectConfiguration
                    {
                        Name           = redirectConfiguration1Name,
                        RedirectType   = ApplicationGatewayRedirectType.Permanent,
                        TargetListener = new SubResource()
                        {
                            Id = GetChildAppGwResourceId(subscriptionId,
                                                         resourceGroupName, appGwName, "httpListeners", httpListener1Name)
                        },
                    },
                    new ApplicationGatewayRedirectConfiguration
                    {
                        Name         = redirectConfiguration2Name,
                        RedirectType = ApplicationGatewayRedirectType.Permanent,
                        TargetUrl    = "http://www.bing.com"
                    }
                },
                //SslCertificates = CreateSslCertificate(sslCertName, "abc")
            };

            return(appGw);
        }
        public override void Execute()
        {
            var rmClient      = new ResourcesManagementClient(Context.SubscriptionId, Context.Credential);
            var computeClient = new ComputeManagementClient(Context.SubscriptionId, Context.Credential);
            var networkClient = new NetworkManagementClient(Context.SubscriptionId, Context.Credential);

            // Create Resource Group
            Console.WriteLine($"--------Start create group {Context.RgName}--------");
            var resourceGroup = rmClient.ResourceGroups.CreateOrUpdate(Context.RgName, new ResourceGroup(Context.Loc)).Value;

            CleanUp.Add(resourceGroup.Id);

            // Create AvailabilitySet
            Console.WriteLine("--------Start create AvailabilitySet--------");
            var aset = new AvailabilitySet(Context.Loc)
            {
                PlatformUpdateDomainCount = 5,
                PlatformFaultDomainCount  = 2,
                Sku = new Azure.ResourceManager.Compute.Models.Sku()
                {
                    Name = "Aligned"
                }
            };

            aset = computeClient.AvailabilitySets.CreateOrUpdate(Context.RgName, Context.VmName + "_aSet", aset).Value;

            // Create VNet
            Console.WriteLine("--------Start create VNet--------");
            string vnetName = Context.VmName + "_vnet";
            var    vnet     = new VirtualNetwork()
            {
                Location     = Context.Loc,
                AddressSpace = new AddressSpace()
                {
                    AddressPrefixes = new List <string>()
                    {
                        "10.0.0.0/16"
                    }
                }
            };

            vnet = networkClient.VirtualNetworks.StartCreateOrUpdate(Context.RgName, vnetName, vnet).WaitForCompletionAsync().ConfigureAwait(false).GetAwaiter().GetResult().Value;

            //create subnet
            Console.WriteLine("--------Start create Subnet--------");
            var nsg = new NetworkSecurityGroup {
                Location = Context.Loc
            };

            nsg.SecurityRules = new List <SecurityRule> {
                new SecurityRule
                {
                    Name                     = "Port80",
                    Priority                 = 1001,
                    Protocol                 = SecurityRuleProtocol.Tcp,
                    Access                   = SecurityRuleAccess.Allow,
                    Direction                = SecurityRuleDirection.Inbound,
                    SourcePortRange          = "*",
                    SourceAddressPrefix      = "*",
                    DestinationPortRange     = "80",
                    DestinationAddressPrefix = "*",
                    Description              = $"Port_80"
                }
            };

            nsg = networkClient.NetworkSecurityGroups.StartCreateOrUpdate(Context.RgName, Context.NsgName, nsg).WaitForCompletionAsync().ConfigureAwait(false).GetAwaiter().GetResult().Value;
            var subnet = new Subnet()
            {
                Name                 = Context.SubnetName,
                AddressPrefix        = "10.0.0.0/24",
                NetworkSecurityGroup = nsg
            };

            subnet = networkClient.Subnets.StartCreateOrUpdate(Context.RgName, vnetName, Context.SubnetName, subnet).WaitForCompletionAsync().ConfigureAwait(false).GetAwaiter().GetResult().Value;
            CreateVmsAsync(resourceGroup, aset, subnet).ConfigureAwait(false).GetAwaiter().GetResult();
        }
Пример #26
0
        /// <summary>
        /// Creates or updates a subnet in the specified virtual network.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group.
        /// </param>
        /// <param name='virtualNetworkName'>
        /// The name of the virtual network.
        /// </param>
        /// <param name='subnetName'>
        /// The name of the subnet.
        /// </param>
        /// <param name='subnetParameters'>
        /// Parameters supplied to the create or update subnet operation.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        public async Task <AzureOperationResponse <Subnet> > CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            // Send Request
            AzureOperationResponse <Subnet> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, subnetParameters, customHeaders, cancellationToken).ConfigureAwait(false);

            return(await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false));
        }
Пример #27
0
    public MyAKS()
    {
        var resourceGroup  = new ResourceGroup("KubTest");
        var randomPassword = new RandomPassword("password", new RandomPasswordArgs
        {
            Length  = 20,
            Special = true,
        }).Result;

        var sshPublicKey = new PrivateKey("ssh-key", new PrivateKeyArgs
        {
            Algorithm = "RSA",
            RsaBits   = 4096,
        }).PublicKeyOpenssh;

        // Create the AD service principal for the K8s cluster.
        var adApp = new Application("aks");
        var adSp  = new ServicePrincipal("aksSp", new ServicePrincipalArgs {
            ApplicationId = adApp.ApplicationId
        });
        var adSpPassword = new ServicePrincipalPassword("aksSpPassword", new ServicePrincipalPasswordArgs
        {
            ServicePrincipalId = adSp.Id,
            Value   = randomPassword,
            EndDate = "2099-01-01T00:00:00Z",
        });

        // Grant networking permissions to the SP (needed e.g. to provision Load Balancers).
        var assignment = new Assignment("role-assignment", new AssignmentArgs
        {
            PrincipalId        = adSp.Id,
            Scope              = resourceGroup.Id,
            RoleDefinitionName = "Network Contributor"
        });

        // Create a Virtual Network for the cluster.
        var vnet = new VirtualNetwork("vnet", new VirtualNetworkArgs
        {
            ResourceGroupName = resourceGroup.Name,
            AddressSpaces     = { "10.2.0.0/16" },
        });

        // Create a Subnet for the cluster.
        var subnet = new Subnet("subnet", new SubnetArgs
        {
            ResourceGroupName  = resourceGroup.Name,
            VirtualNetworkName = vnet.Name,
            AddressPrefix      = "10.2.1.0/24",
        });

        // Now allocate an AKS cluster.
        var cluster = new KubernetesCluster("aksCluster", new KubernetesClusterArgs
        {
            ResourceGroupName = resourceGroup.Name,
            //PrivateClusterEnabled = true,
            DefaultNodePool = new KubernetesClusterDefaultNodePoolArgs
            {
                Name         = "aksagentpool",
                NodeCount    = 3,
                VmSize       = "Standard_B2s",
                OsDiskSizeGb = 30,
                VnetSubnetId = subnet.Id
            },
            DnsPrefix    = "sampleaks",
            LinuxProfile = new KubernetesClusterLinuxProfileArgs
            {
                AdminUsername = "******",
                SshKey        = new KubernetesClusterLinuxProfileSshKeyArgs
                {
                    KeyData = sshPublicKey,
                },
            },
            ServicePrincipal = new KubernetesClusterServicePrincipalArgs
            {
                ClientId     = adApp.ApplicationId,
                ClientSecret = adSpPassword.Value,
            },
            KubernetesVersion      = "1.17.9",
            RoleBasedAccessControl = new KubernetesClusterRoleBasedAccessControlArgs {
                Enabled = true
            },
            NetworkProfile = new KubernetesClusterNetworkProfileArgs
            {
                NetworkPlugin    = "azure",
                DnsServiceIp     = "10.2.2.254",
                ServiceCidr      = "10.2.2.0/24",
                DockerBridgeCidr = "172.17.0.1/16",
            },
        });

        // Create a k8s provider pointing to the kubeconfig.
        var k8sProvider = new Pulumi.Kubernetes.Provider("k8s", new Pulumi.Kubernetes.ProviderArgs
        {
            KubeConfig = cluster.KubeConfigRaw
        });

        var customResourceOptions = new CustomResourceOptions
        {
            Provider = k8sProvider
        };

        // Create a Container Registry.
        var registry = new Registry("acregistry", new RegistryArgs
        {
            ResourceGroupName = resourceGroup.Name,
            Sku          = "Basic",
            AdminEnabled = true
        });

        //Build & push the sample application to the registry.
        var applicationName = "gol";
        var imageName       = registry.LoginServer.Apply(value => $"{value}/{applicationName}");

        var image = new Image(applicationName, new ImageArgs
        {
            Build    = "./gol",
            Registry = new ImageRegistry
            {
                Server   = registry.LoginServer,
                Username = registry.AdminUsername,
                Password = registry.AdminPassword
            },
            ImageName = imageName
        }, new ComponentResourceOptions
        {
            Provider = k8sProvider
        });

        //Create a k8s secret for use when pulling images from the container registry when deploying the application.
        var dockerCfg = Output.All <string>(registry.LoginServer, registry.AdminUsername, registry.AdminPassword).Apply(
            values =>
        {
            var r        = new Dictionary <string, object>();
            var server   = values[0];
            var username = values[1];
            var password = values[2];

            r[server] = new
            {
                email = "*****@*****.**",
                username,
                password
            };

            return(r);
        });

        var dockerCfgString = dockerCfg.Apply(x =>
                                              Convert.ToBase64String(Encoding.UTF8.GetBytes(System.Text.Json.JsonSerializer.Serialize(x))));

        var dockerCfgSecretName = "dockercfg-secret";

        var dockerCfgSecret = new Pulumi.Kubernetes.Core.V1.Secret(dockerCfgSecretName, new SecretArgs
        {
            Data =
            {
                { ".dockercfg", dockerCfgString }
            },
            Type     = "kubernetes.io/dockercfg",
            Metadata = new ObjectMetaArgs
            {
                Name = dockerCfgSecretName,
            }
        }, customResourceOptions);

        //Deploy the application to the cluster.
        var labels = new InputMap <string>
        {
            { "app", $"app-{applicationName}" },
        };

        var deployment = new Pulumi.Kubernetes.Apps.V1.Deployment(applicationName, new DeploymentArgs
        {
            Spec = new DeploymentSpecArgs
            {
                Selector = new LabelSelectorArgs
                {
                    MatchLabels = labels,
                },
                Replicas = 1,
                Template = new PodTemplateSpecArgs
                {
                    Metadata = new ObjectMetaArgs
                    {
                        Labels = labels,
                        Name   = applicationName
                    },
                    Spec = new PodSpecArgs
                    {
                        Containers = new List <ContainerArgs>
                        {
                            new ContainerArgs
                            {
                                Name  = applicationName,
                                Image = image.ImageName,
                            }
                        },
                        ImagePullSecrets = new LocalObjectReferenceArgs
                        {
                            Name = dockerCfgSecretName
                        }
                    }
                }
            }
        }, customResourceOptions);

        //Create a new service.
        var service = new Pulumi.Kubernetes.Core.V1.Service(applicationName, new ServiceArgs
        {
            Metadata = new ObjectMetaArgs
            {
                Name   = applicationName,
                Labels = labels
            },
            Spec = new ServiceSpecArgs
            {
                Type     = "LoadBalancer",
                Selector = deployment.Spec.Apply(x => x.Template.Metadata.Labels),
                Ports    = new ServicePortArgs
                {
                    Port = 80
                }
            }
        }, customResourceOptions);

        this.KubeConfig          = cluster.KubeConfigRaw;
        this.DockercfgSecretName = dockerCfgSecret.Metadata.Apply(x => x.Name);
    }
Пример #28
0
        /// <summary>
        /// Creates or updates a subnet in the specified virtual network.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group.
        /// </param>
        /// <param name='virtualNetworkName'>
        /// The name of the virtual network.
        /// </param>
        /// <param name='subnetName'>
        /// The name of the subnet.
        /// </param>
        /// <param name='subnetParameters'>
        /// Parameters supplied to the create or update subnet operation.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <AzureOperationResponse <Subnet> > BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (resourceGroupName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
            }
            if (virtualNetworkName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName");
            }
            if (subnetName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "subnetName");
            }
            if (subnetParameters == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "subnetParameters");
            }
            if (Client.ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }
            if (Client.SubscriptionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("virtualNetworkName", virtualNetworkName);
                tracingParameters.Add("subnetName", subnetName);
                tracingParameters.Add("subnetParameters", subnetParameters);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}").ToString();

            _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
            _url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName));
            _url = _url.Replace("{subnetName}", System.Uri.EscapeDataString(subnetName));
            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
            List <string> _queryParameters = new List <string>();

            if (Client.ApiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
            }
            if (_queryParameters.Count > 0)
            {
                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("PUT");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
            }


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            if (subnetParameters != null)
            {
                _requestContent      = Rest.Serialization.SafeJsonConvert.SerializeObject(subnetParameters, Client.SerializationSettings);
                _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            }
            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200 && (int)_statusCode != 201)
            {
                var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <CloudError>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex      = new CloudException(_errorBody.Message);
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_httpResponse.Headers.Contains("x-ms-request-id"))
                {
                    ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                }
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse <Subnet>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <Subnet>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            // Deserialize Response
            if ((int)_statusCode == 201)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <Subnet>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
        public void TestNicVirtualMachineReference()
        {
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                EnsureClientsInitialized(context);

                ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true);

                string         rgName             = ComputeManagementTestUtilities.GenerateName(TestPrefix);
                string         asName             = ComputeManagementTestUtilities.GenerateName("as");
                string         storageAccountName = ComputeManagementTestUtilities.GenerateName(TestPrefix);
                VirtualMachine inputVM;
                try
                {
                    // Create the resource Group, it might have been already created during StorageAccount creation.
                    var resourceGroup = m_ResourcesClient.ResourceGroups.CreateOrUpdate(
                        rgName,
                        new ResourceGroup
                    {
                        Location = m_location,
                        Tags     = new Dictionary <string, string>()
                        {
                            { rgName, DateTime.UtcNow.ToString("u") }
                        }
                    });

                    // Create Storage Account, so that both the VMs can share it
                    var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName);

                    Subnet subnetResponse = CreateVNET(rgName);

                    NetworkInterface nicResponse = CreateNIC(rgName, subnetResponse, null);

                    string asetId = CreateAvailabilitySet(rgName, asName);

                    inputVM = CreateDefaultVMInput(rgName, storageAccountName, imageRef, asetId, nicResponse.Id);

                    string expectedVMReferenceId = Helpers.GetVMReferenceId(m_subId, rgName, inputVM.Name);

                    var createOrUpdateResponse = m_CrpClient.VirtualMachines.CreateOrUpdate(
                        rgName, inputVM.Name, inputVM);

                    Assert.NotNull(createOrUpdateResponse);

                    var getVMResponse = m_CrpClient.VirtualMachines.Get(rgName, inputVM.Name);

                    Assert.True(
                        getVMResponse.AvailabilitySet.Id
                        .ToLowerInvariant() == asetId.ToLowerInvariant());
                    ValidateVM(inputVM, getVMResponse, expectedVMReferenceId);

                    var getNicResponse = m_NrpClient.NetworkInterfaces.Get(rgName, nicResponse.Name);
                    // TODO AutoRest: Recording Passed, but these assertions failed in Playback mode
                    Assert.NotNull(getNicResponse.MacAddress);
                    Assert.NotNull(getNicResponse.Primary);
                    Assert.True(getNicResponse.Primary != null && getNicResponse.Primary.Value);
                }
                finally
                {
                    // Cleanup the created resources
                    m_ResourcesClient.ResourceGroups.Delete(rgName);
                }
            }
        }
Пример #30
0
        public void UpdateSubnets(List <Wire> added, List <Wire> removed)
        {
            List <Subnet> checkSplitSubnets = new List <Subnet>();

            foreach (var old in removed)
            {
                var startNet = FindSubnet(old.Pos);
                var endNet   = FindSubnet(old.EndPos);

                // This is null if there was an error removing the wire
                Subnet?removedFromSubnet;
                if (startNet != null && endNet != null)
                {
                    if (startNet == endNet)
                    {
                        // We are removing a wire from a subnet
                        // So here we want to figure out if we have to split this subnet
                        startNet.RemoveWire(old);

                        // If there are wires left, we need to check if
                        // the deletion led to any splits in the subnet
                        if (startNet.Wires.Count > 0)
                        {
                            if (checkSplitSubnets.Contains(startNet) == false)
                            {
                                checkSplitSubnets.Add(startNet);
                            }
                        }

                        removedFromSubnet = startNet;
                    }
                    else
                    {
                        // This is f***ed in more ways than one...
                        Console.WriteLine($"Error! This should not happen! Trying to remove a wire containing to more than one subnet! (Wire: {old}, Subnet1: {startNet}, Subnet2:{endNet})");
                        removedFromSubnet = null;
                    }
                }
                else if (startNet != null)
                {
                    // We are removing from one subnet
                    if (startNet.RemoveWire(old))
                    {
                        Console.WriteLine($"Warn: Tried to remove a wire from a subnet that didn't contain that wire. (Wire: {old}, Subnet: {startNet})");
                    }

                    removedFromSubnet = startNet;

                    Console.WriteLine($"Removed wire to subnet: {startNet}");
                }
                else if (endNet != null)
                {
                    // We are removing from one subnet
                    if (endNet.RemoveWire(old))
                    {
                        Console.WriteLine($"Warn: Tried to remove a wire from a subnet that didn't contain that wire. (Wire: {old}, Subnet: {endNet})");
                    }

                    removedFromSubnet = endNet;

                    Console.WriteLine($"Removed wire to subnet: {endNet}");
                }
                else
                {
                    // Here we are removing a wire that didn't belong to any subnet!?
                    Console.WriteLine($"Error! This should not happen! Trying to remove a wire not contained in any subnet! (Wire: {old})");
                    removedFromSubnet = null;
                }

                // If we removed a wire from a subnet, check if we need to deleted that subnet
                if (removedFromSubnet?.Wires.Count <= 0)
                {
                    Console.WriteLine($"Removed subnet: {removedFromSubnet}");
                    LogikUI.Simulation.RemoveSubnet(removedFromSubnet.ID);
                    removedFromSubnet.ID = SubnetID.Invalid;

                    Subnets.Remove(removedFromSubnet);
                }
            }

            List <Subnet>         addedSubnets = new List <Subnet>();
            List <(Wire, Subnet)> addedWiresAndTheirNewSubnet = new List <(Wire, Subnet)>();

            foreach (var @new in added)
            {
                var startNet = FindSubnet(@new.Pos);
                var endNet   = FindSubnet(@new.EndPos);

                Subnet subnetAddedTo;
                if (startNet != null && endNet != null)
                {
                    if (startNet == endNet)
                    {
                        // Here they are the same subnet.
                        // So we just add the wire.
                        startNet.AddWire(@new);
                        subnetAddedTo = startNet;
                    }
                    else
                    {
                        // Figure out what subnet to merge into.
                        var(merged, mergee) = startNet.ID != 0 ?
                                              (startNet, endNet) :
                                              (endNet, startNet);

                        Console.WriteLine($"Merging subnet ({mergee}) into subnet ({merged}).");
                        Subnets.Remove(mergee);
                        merged.Merge(mergee);

                        // Transfer over all of the added wires if there are any
                        for (int i = 0; i < addedWiresAndTheirNewSubnet.Count; i++)
                        {
                            var(wire, subnet) = addedWiresAndTheirNewSubnet[i];
                            if (subnet == mergee)
                            {
                                addedWiresAndTheirNewSubnet[i] = (wire, merged);
                            }
                        }

                        // Don't forget to add the wire that merged these subnets
                        merged.AddWire(@new);
                        subnetAddedTo = merged;

                        Console.WriteLine($"\tResult: {merged}");
                    }
                }
                else if (startNet != null)
                {
                    // Here we just add this wire to the subnet,
                    // it's not going to change anything.
                    startNet.AddWire(@new);
                    subnetAddedTo = startNet;
                    Console.WriteLine($"Added wire to subnet: {startNet}");
                }
                else if (endNet != null)
                {
                    // Here we just add this wire to the subnet,
                    // it's not going to change anything.
                    endNet.AddWire(@new);
                    subnetAddedTo = endNet;
                    Console.WriteLine($"Added wire to subnet: {endNet}");
                }
                else
                {
                    // This means that this wire should be in it's own subnet.
                    // It might get merged into another subnet later though..
                    var sub = new Subnet(0);
                    sub.AddWire(@new);

                    addedSubnets.Add(sub);

                    // NOTE: do we want to do this?
                    Subnets.Add(sub);

                    subnetAddedTo = sub;
                    Console.WriteLine($"Added single wire subnet: {sub}");
                }

                addedWiresAndTheirNewSubnet.Add((@new, subnetAddedTo));
            }

            // Because we have figured out all of the merging we know
            // that all of the subnets in this list will have their own
            // id. When splitting we can only ever create new subnets
            // so we don't have to worry about merging so we give those
            // subnets their id directly when they are created.
            foreach (var addedNet in addedSubnets)
            {
                // Here we should figure out a new subnet id
                addedNet.ID = (SubnetID)SubnetIDCounter++;
                LogikUI.Simulation.AddSubnet(addedNet.ID);
                Console.WriteLine($"Added new subnet: {addedNet}");
            }

            // Here we go though all new wires and their subnet to see if the new wires
            // connects any new components to the subnet.
            foreach (var(wire, subnet) in addedWiresAndTheirNewSubnet)
            {
                foreach (var comp in Gates.Instances)
                {
                    // FIXME: This stackalloc is going to blow up...
                    Span <Vector2i> portLocs = stackalloc Vector2i[Gates.GetNumberOfPorts(comp)];
                    Gates.GetTransformedPorts(comp, portLocs);

                    for (int i = 0; i < portLocs.Length; i++)
                    {
                        var loc = portLocs[i];
                        if (wire.IsConnectionPoint(loc))
                        {
                            if (subnet.ComponentPorts.Contains((comp, i)) == false)
                            {
                                subnet.AddComponent(comp, i);
                                Console.WriteLine($"Added component ({comp}, port: {i}) to the subnet: {subnet}.");
                            }
                        }
                    }
                }
            }

            // Here we check all of the splitting that needs to be done.
            foreach (var split in checkSplitSubnets)
            {
                // Here we need to check if this subnet
                // has to be split into multiple subnets

                if (split.ID == 0)
                {
                    Console.WriteLine($"We don't need to check for splits on this subnet because it has been removed! Subnet: {split}");
                    continue;
                }

                if (split.Wires.Count == 0)
                {
                    Console.WriteLine($"We don't need to try to split a subnet without wires. Subnet: {split}");
                    continue;
                }

                Console.WriteLine($"Checking subnet ({split}) for splits!");

                List <Wire> wiresLeft = new List <Wire>(split.Wires);

                bool assignedOriginal = false;
                var  newSubnets       = new List <Subnet>();

                while (wiresLeft.Count > 0)
                {
 internal PrivateLinkServiceIpConfiguration(string id, string name, string etag, string type, string privateIPAddress, IPAllocationMethod?privateIPAllocationMethod, Subnet subnet, bool?primary, ProvisioningState?provisioningState, IPVersion?privateIPAddressVersion) : base(id)
 {
     Name                      = name;
     Etag                      = etag;
     Type                      = type;
     PrivateIPAddress          = privateIPAddress;
     PrivateIPAllocationMethod = privateIPAllocationMethod;
     Subnet                    = subnet;
     Primary                   = primary;
     ProvisioningState         = provisioningState;
     PrivateIPAddressVersion   = privateIPAddressVersion;
 }
Пример #32
0
        public static void connectToPB(Project project, int sourceDevice, int targetDevice)
        {
            var allDevices = project.Devices;

            //creating subnet to not connected
            SubnetComposition subnets = project.Subnets;

            Subnet newSubnet = subnets.Create("System:Subnet.Profibus", "Profibus Subnet_" + Guid.NewGuid().ToString());

            //subnet typeIdentifiers can be .Profibus, .Mpi, .Asi

            //source device
            Device device2 = DeviceMethods.GetDevice(project, targetDevice);
            Device device1 = DeviceMethods.GetDevice(project, sourceDevice);

            DeviceItem head1 = null;
            DeviceItem head2 = null;

            DeviceItem interface1 = null;

            if (device1.Name.Contains("PLC"))
            {
                head1 = DeviceItemMethods.GetPlcHead(device1);

                interface1 =
                    (from DeviceItem di in head1.DeviceItems
                     where di.Name.Contains("DP")
                     select di).First();
            }

            else
            {
                head1 = DeviceItemMethods.GetHead(device1);

                interface1 =
                    (from DeviceItem di in head1.DeviceItems
                     where di.Name.Equals(head1.Name)
                     select di).First();
            }

            NetworkInterface interfacePN1  = interface1.GetService <NetworkInterface>();
            NodeComposition  networkNodes1 = interfacePN1.Nodes;

            //IoController plcIoController = interfacePN1.IoControllers.First();
            //IoSystem plcIoSystem = plcIoController?.CreateIoSystem("myIoSystem" + Guid.NewGuid().ToString());
            //IoConnector ioConnector = null; //IoController feature is in construction

            networkNodes1.First().ConnectToSubnet(newSubnet);

            DeviceItem interface2 = null;

            if (device2.Name.Contains("PLC"))
            {
                head2 = DeviceItemMethods.GetPlcHead(device2);

                interface2 =
                    (from DeviceItem di in head2.DeviceItems
                     where di.Name.Contains("DP")
                     select di).First();
            }

            else
            {
                head2 = DeviceItemMethods.GetHead(device2);
                foreach (DeviceItem di in head2.DeviceItems)
                {
                    Console.WriteLine("------------------" + di.Name);
                }


                interface2 =
                    (from DeviceItem di in head2.DeviceItems
                     where di.Name.Equals(head2.Name)
                     select di).First();
            }


            NetworkInterface interfacePN2  = interface2.GetService <NetworkInterface>();
            NodeComposition  networkNodes2 = interfacePN2.Nodes;

            networkNodes2.First().ConnectToSubnet(newSubnet);   //second device connection


            Console.WriteLine("Connected to " + newSubnet.GetAttribute("Name"));
        }