private PSAutoscaleSetting CreateCompleteSpec(string location, string name, List <AutoscaleProfile> profiles = null)
        {
            if (profiles == null)
            {
                profiles = new List <AutoscaleProfile>()
                {
                    this.CreateAutoscaleProfile()
                };
            }

            var settingProperty = new AutoscaleSetting
            {
                Name              = name,
                Enabled           = true,
                Profiles          = profiles,
                TargetResourceUri = Utilities.ResourceUri
            };

            var setting = new AutoscaleSettingResource
            {
                Location   = location,
                Name       = name,
                Properties = new PSAutoscaleSettingProperty(settingProperty),
                Tags       = new LazyDictionary <string, string>()
            };

            return(new PSAutoscaleSetting(setting));
        }
Beispiel #2
0
 /// <summary>
 /// Initializes an instance of the PSAutoscaleSettingProperty class.
 /// </summary>
 /// <param name="autoscaleSetting">The autoscale setting to use as base</param>
 public PSAutoscaleSettingProperty(AutoscaleSetting autoscaleSetting)
 {
     if (autoscaleSetting != null)
     {
         this.Enabled           = autoscaleSetting.Enabled;
         this.Name              = autoscaleSetting.Name;
         this.Profiles          = autoscaleSetting.Profiles;
         this.TargetResourceUri = autoscaleSetting.TargetResourceUri;
     }
 }
Beispiel #3
0
        private static void AreEqual(AutoscaleSetting exp, AutoscaleSetting act)
        {
            if (exp != null)
            {
                Assert.Equal(exp.Enabled, act.Enabled);
                Assert.Equal(exp.Name, act.Name);
                Assert.Equal(exp.TargetResourceUri, act.TargetResourceUri);

                for (int i = 0; i < exp.Profiles.Count; i++)
                {
                    var expectedProfile = exp.Profiles[i];
                    var actualProfile   = act.Profiles[i];
                    AreEqual(expectedProfile, actualProfile);
                }
            }
        }
Beispiel #4
0
        /// <param name='resourceId'>
        /// Required. The resource ID.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.Monitoring.Autoscale.Models.AutoscaleSettingGetResponse> GetAsync(string resourceId, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceId == null)
            {
                throw new ArgumentNullException("resourceId");
            }

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = Tracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("resourceId", resourceId);
                Tracing.Enter(invocationId, this, "GetAsync", tracingParameters);
            }

            // Construct URL
            string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/monitoring/autoscalesettings?";

            url = url + "resourceId=" + Uri.EscapeDataString(resourceId.Trim());
            string baseUrl = this.Client.BaseUri.AbsoluteUri;

            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

            try
            {
                httpRequest            = new HttpRequestMessage();
                httpRequest.Method     = HttpMethod.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers
                httpRequest.Headers.Add("Accept", "application/json");
                httpRequest.Headers.Add("x-ms-version", "2013-10-01");

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        Tracing.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        Tracing.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    AutoscaleSettingGetResponse result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    result = new AutoscaleSettingGetResponse();
                    JToken responseDoc = null;
                    if (string.IsNullOrEmpty(responseContent) == false)
                    {
                        responseDoc = JToken.Parse(responseContent);
                    }

                    if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                    {
                        AutoscaleSetting settingInstance = new AutoscaleSetting();
                        result.Setting = settingInstance;

                        JToken profilesArray = responseDoc["Profiles"];
                        if (profilesArray != null && profilesArray.Type != JTokenType.Null)
                        {
                            foreach (JToken profilesValue in ((JArray)profilesArray))
                            {
                                AutoscaleProfile autoscaleProfileInstance = new AutoscaleProfile();
                                settingInstance.Profiles.Add(autoscaleProfileInstance);

                                JToken nameValue = profilesValue["Name"];
                                if (nameValue != null && nameValue.Type != JTokenType.Null)
                                {
                                    string nameInstance = ((string)nameValue);
                                    autoscaleProfileInstance.Name = nameInstance;
                                }

                                JToken capacityValue = profilesValue["Capacity"];
                                if (capacityValue != null && capacityValue.Type != JTokenType.Null)
                                {
                                    ScaleCapacity capacityInstance = new ScaleCapacity();
                                    autoscaleProfileInstance.Capacity = capacityInstance;

                                    JToken minimumValue = capacityValue["Minimum"];
                                    if (minimumValue != null && minimumValue.Type != JTokenType.Null)
                                    {
                                        string minimumInstance = ((string)minimumValue);
                                        capacityInstance.Minimum = minimumInstance;
                                    }

                                    JToken maximumValue = capacityValue["Maximum"];
                                    if (maximumValue != null && maximumValue.Type != JTokenType.Null)
                                    {
                                        string maximumInstance = ((string)maximumValue);
                                        capacityInstance.Maximum = maximumInstance;
                                    }

                                    JToken defaultValue = capacityValue["Default"];
                                    if (defaultValue != null && defaultValue.Type != JTokenType.Null)
                                    {
                                        string defaultInstance = ((string)defaultValue);
                                        capacityInstance.Default = defaultInstance;
                                    }
                                }

                                JToken rulesArray = profilesValue["Rules"];
                                if (rulesArray != null && rulesArray.Type != JTokenType.Null)
                                {
                                    foreach (JToken rulesValue in ((JArray)rulesArray))
                                    {
                                        ScaleRule scaleRuleInstance = new ScaleRule();
                                        autoscaleProfileInstance.Rules.Add(scaleRuleInstance);

                                        JToken metricTriggerValue = rulesValue["MetricTrigger"];
                                        if (metricTriggerValue != null && metricTriggerValue.Type != JTokenType.Null)
                                        {
                                            MetricTrigger metricTriggerInstance = new MetricTrigger();
                                            scaleRuleInstance.MetricTrigger = metricTriggerInstance;

                                            JToken metricNameValue = metricTriggerValue["MetricName"];
                                            if (metricNameValue != null && metricNameValue.Type != JTokenType.Null)
                                            {
                                                string metricNameInstance = ((string)metricNameValue);
                                                metricTriggerInstance.MetricName = metricNameInstance;
                                            }

                                            JToken metricNamespaceValue = metricTriggerValue["MetricNamespace"];
                                            if (metricNamespaceValue != null && metricNamespaceValue.Type != JTokenType.Null)
                                            {
                                                string metricNamespaceInstance = ((string)metricNamespaceValue);
                                                metricTriggerInstance.MetricNamespace = metricNamespaceInstance;
                                            }

                                            JToken metricSourceValue = metricTriggerValue["MetricSource"];
                                            if (metricSourceValue != null && metricSourceValue.Type != JTokenType.Null)
                                            {
                                                string metricSourceInstance = ((string)metricSourceValue);
                                                metricTriggerInstance.MetricSource = metricSourceInstance;
                                            }

                                            JToken timeGrainValue = metricTriggerValue["TimeGrain"];
                                            if (timeGrainValue != null && timeGrainValue.Type != JTokenType.Null)
                                            {
                                                TimeSpan timeGrainInstance = TypeConversion.From8601TimeSpan(((string)timeGrainValue));
                                                metricTriggerInstance.TimeGrain = timeGrainInstance;
                                            }

                                            JToken statisticValue = metricTriggerValue["Statistic"];
                                            if (statisticValue != null && statisticValue.Type != JTokenType.Null)
                                            {
                                                MetricStatisticType statisticInstance = ((MetricStatisticType)Enum.Parse(typeof(MetricStatisticType), ((string)statisticValue), true));
                                                metricTriggerInstance.Statistic = statisticInstance;
                                            }

                                            JToken timeWindowValue = metricTriggerValue["TimeWindow"];
                                            if (timeWindowValue != null && timeWindowValue.Type != JTokenType.Null)
                                            {
                                                TimeSpan timeWindowInstance = TypeConversion.From8601TimeSpan(((string)timeWindowValue));
                                                metricTriggerInstance.TimeWindow = timeWindowInstance;
                                            }

                                            JToken timeAggregationValue = metricTriggerValue["TimeAggregation"];
                                            if (timeAggregationValue != null && timeAggregationValue.Type != JTokenType.Null)
                                            {
                                                TimeAggregationType timeAggregationInstance = ((TimeAggregationType)Enum.Parse(typeof(TimeAggregationType), ((string)timeAggregationValue), true));
                                                metricTriggerInstance.TimeAggregation = timeAggregationInstance;
                                            }

                                            JToken operatorValue = metricTriggerValue["Operator"];
                                            if (operatorValue != null && operatorValue.Type != JTokenType.Null)
                                            {
                                                ComparisonOperationType operatorInstance = ((ComparisonOperationType)Enum.Parse(typeof(ComparisonOperationType), ((string)operatorValue), true));
                                                metricTriggerInstance.Operator = operatorInstance;
                                            }

                                            JToken thresholdValue = metricTriggerValue["Threshold"];
                                            if (thresholdValue != null && thresholdValue.Type != JTokenType.Null)
                                            {
                                                double thresholdInstance = ((double)thresholdValue);
                                                metricTriggerInstance.Threshold = thresholdInstance;
                                            }
                                        }

                                        JToken scaleActionValue = rulesValue["ScaleAction"];
                                        if (scaleActionValue != null && scaleActionValue.Type != JTokenType.Null)
                                        {
                                            ScaleAction scaleActionInstance = new ScaleAction();
                                            scaleRuleInstance.ScaleAction = scaleActionInstance;

                                            JToken directionValue = scaleActionValue["Direction"];
                                            if (directionValue != null && directionValue.Type != JTokenType.Null)
                                            {
                                                ScaleDirection directionInstance = ((ScaleDirection)Enum.Parse(typeof(ScaleDirection), ((string)directionValue), true));
                                                scaleActionInstance.Direction = directionInstance;
                                            }

                                            JToken typeValue = scaleActionValue["Type"];
                                            if (typeValue != null && typeValue.Type != JTokenType.Null)
                                            {
                                                ScaleType typeInstance = ((ScaleType)Enum.Parse(typeof(ScaleType), ((string)typeValue), true));
                                                scaleActionInstance.Type = typeInstance;
                                            }

                                            JToken valueValue = scaleActionValue["Value"];
                                            if (valueValue != null && valueValue.Type != JTokenType.Null)
                                            {
                                                string valueInstance = ((string)valueValue);
                                                scaleActionInstance.Value = valueInstance;
                                            }

                                            JToken cooldownValue = scaleActionValue["Cooldown"];
                                            if (cooldownValue != null && cooldownValue.Type != JTokenType.Null)
                                            {
                                                TimeSpan cooldownInstance = TypeConversion.From8601TimeSpan(((string)cooldownValue));
                                                scaleActionInstance.Cooldown = cooldownInstance;
                                            }
                                        }
                                    }
                                }

                                JToken fixedDateValue = profilesValue["FixedDate"];
                                if (fixedDateValue != null && fixedDateValue.Type != JTokenType.Null)
                                {
                                    TimeWindow fixedDateInstance = new TimeWindow();
                                    autoscaleProfileInstance.FixedDate = fixedDateInstance;

                                    JToken timeZoneValue = fixedDateValue["TimeZone"];
                                    if (timeZoneValue != null && timeZoneValue.Type != JTokenType.Null)
                                    {
                                        string timeZoneInstance = ((string)timeZoneValue);
                                        fixedDateInstance.TimeZone = timeZoneInstance;
                                    }

                                    JToken startValue = fixedDateValue["Start"];
                                    if (startValue != null && startValue.Type != JTokenType.Null)
                                    {
                                        DateTime startInstance = ((DateTime)startValue);
                                        fixedDateInstance.Start = startInstance;
                                    }

                                    JToken endValue = fixedDateValue["End"];
                                    if (endValue != null && endValue.Type != JTokenType.Null)
                                    {
                                        DateTime endInstance = ((DateTime)endValue);
                                        fixedDateInstance.End = endInstance;
                                    }
                                }

                                JToken recurrenceValue = profilesValue["Recurrence"];
                                if (recurrenceValue != null && recurrenceValue.Type != JTokenType.Null)
                                {
                                    Recurrence recurrenceInstance = new Recurrence();
                                    autoscaleProfileInstance.Recurrence = recurrenceInstance;

                                    JToken frequencyValue = recurrenceValue["Frequency"];
                                    if (frequencyValue != null && frequencyValue.Type != JTokenType.Null)
                                    {
                                        RecurrenceFrequency frequencyInstance = ((RecurrenceFrequency)Enum.Parse(typeof(RecurrenceFrequency), ((string)frequencyValue), true));
                                        recurrenceInstance.Frequency = frequencyInstance;
                                    }

                                    JToken scheduleValue = recurrenceValue["Schedule"];
                                    if (scheduleValue != null && scheduleValue.Type != JTokenType.Null)
                                    {
                                        RecurrentSchedule scheduleInstance = new RecurrentSchedule();
                                        recurrenceInstance.Schedule = scheduleInstance;

                                        JToken timeZoneValue2 = scheduleValue["TimeZone"];
                                        if (timeZoneValue2 != null && timeZoneValue2.Type != JTokenType.Null)
                                        {
                                            string timeZoneInstance2 = ((string)timeZoneValue2);
                                            scheduleInstance.TimeZone = timeZoneInstance2;
                                        }

                                        JToken daysArray = scheduleValue["Days"];
                                        if (daysArray != null && daysArray.Type != JTokenType.Null)
                                        {
                                            foreach (JToken daysValue in ((JArray)daysArray))
                                            {
                                                scheduleInstance.Days.Add(((string)daysValue));
                                            }
                                        }

                                        JToken hoursArray = scheduleValue["Hours"];
                                        if (hoursArray != null && hoursArray.Type != JTokenType.Null)
                                        {
                                            foreach (JToken hoursValue in ((JArray)hoursArray))
                                            {
                                                scheduleInstance.Hours.Add(((int)hoursValue));
                                            }
                                        }

                                        JToken minutesArray = scheduleValue["Minutes"];
                                        if (minutesArray != null && minutesArray.Type != JTokenType.Null)
                                        {
                                            foreach (JToken minutesValue in ((JArray)minutesArray))
                                            {
                                                scheduleInstance.Minutes.Add(((int)minutesValue));
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        JToken enabledValue = responseDoc["Enabled"];
                        if (enabledValue != null && enabledValue.Type != JTokenType.Null)
                        {
                            bool enabledInstance = ((bool)enabledValue);
                            settingInstance.Enabled = enabledInstance;
                        }
                    }

                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
Beispiel #5
0
        public Func <RegionalContext, IRegionalEndpoint> BuildVMScaleSetApp(GlobalContext context)
        {
            var options = (CustomResourceOptions)ResourceOptions.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 LoadBalancerFrontendIpConfigurationsArgs
                        {
                            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 ScaleSetNetworkProfilesArgs
                        {
                            IpConfigurations =
                            {
                                new ScaleSetNetworkProfilesIpConfigurationsArgs
                                {
                                    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 ScaleSetStorageProfileDataDisksArgs
                        {
                            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)ResourceOptions.Merge(options, new ResourceOptions {
                    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 AutoscaleSettingProfilesArgs
                        {
                            Capacity = new AutoscaleSettingProfilesCapacityArgs
                            {
                                Default = 1,
                                Maximum = 10,
                                Minimum = 1,
                            },
                            Name = "defaultProfile",
                            Rules =
                            {
                                new AutoscaleSettingProfilesRulesArgs
                                {
                                    MetricTrigger = new AutoscaleSettingProfilesRulesMetricTriggerArgs
                                    {
                                        MetricName = "Percentage CPU",
                                        MetricResourceId = scaleSet.Id,
                                        Operator = "GreaterThan",
                                        Statistic = "Average",
                                        Threshold = 75,
                                        TimeAggregation = "Average",
                                        TimeGrain = "PT1M",
                                        TimeWindow = "PT5M",
                                    },
                                    ScaleAction = new AutoscaleSettingProfilesRulesScaleActionArgs
                                    {
                                        Cooldown = "PT1M",
                                        Direction = "Increase",
                                        Type = "ChangeCount",
                                        Value = 1,
                                    },
                                },
                                new AutoscaleSettingProfilesRulesArgs
                                {
                                    MetricTrigger = new AutoscaleSettingProfilesRulesMetricTriggerArgs
                                    {
                                        MetricName = "Percentage CPU",
                                        MetricResourceId = scaleSet.Id,
                                        Operator = "LessThan",
                                        Statistic = "Average",
                                        Threshold = 25,
                                        TimeAggregation = "Average",
                                        TimeGrain = "PT1M",
                                        TimeWindow = "PT5M",
                                    },
                                    ScaleAction = new AutoscaleSettingProfilesRulesScaleActionArgs
                                    {
                                        Cooldown = "PT1M",
                                        Direction = "Decrease",
                                        Type = "ChangeCount",
                                        Value = 1,
                                    },
                                },
                            }
                        }
                    },
                    TargetResourceId = scaleSet.Id,
                },
                                                     options);

                return new AzureEndpoint(publicIp.Id);
            });
        }
Beispiel #6
0
    public VmScalesetStack()
    {
        var applicationPort = 80;
        var resourceGroup   = new ResourceGroup("vmss-rg");

        var network = new VirtualNetwork("vnet",
                                         new VirtualNetworkArgs
        {
            ResourceGroupName = resourceGroup.Name,
            AddressSpaces     = { "10.0.0.0/16" }
        }
                                         );

        var subnet = new Subnet("subnet",
                                new SubnetArgs
        {
            ResourceGroupName = resourceGroup.Name,
            Name               = "default",
            AddressPrefixes    = "10.0.1.0/24",
            VirtualNetworkName = network.Name
        });

        var publicIp = new PublicIp("public-ip",
                                    new PublicIpArgs
        {
            ResourceGroupName = resourceGroup.Name,
            AllocationMethod  = "Dynamic"
        });

        var lb = new LoadBalancer("lb",
                                  new LoadBalancerArgs
        {
            ResourceGroupName        = resourceGroup.Name,
            FrontendIpConfigurations = new List <LoadBalancerFrontendIpConfigurationArgs>
            {
                new LoadBalancerFrontendIpConfigurationArgs
                {
                    Name = "PublicIPAddress",
                    PublicIpAddressId = publicIp.Id
                }
            }
        });

        var bpePool = new BackendAddressPool("bpepool",
                                             new BackendAddressPoolArgs
        {
            ResourceGroupName = resourceGroup.Name,
            LoadbalancerId    = lb.Id,
        });

        var sshProbe = new Probe("ssh-probe",
                                 new ProbeArgs
        {
            ResourceGroupName = resourceGroup.Name,
            LoadbalancerId    = lb.Id,
            Port = applicationPort,
        });

        var natRule = new Rule("lbnatrule-http",
                               new RuleArgs
        {
            ResourceGroupName           = resourceGroup.Name,
            BackendAddressPoolId        = bpePool.Id,
            BackendPort                 = applicationPort,
            FrontendIpConfigurationName = "PublicIPAddress",
            FrontendPort                = applicationPort,
            LoadbalancerId              = lb.Id,
            ProbeId  = sshProbe.Id,
            Protocol = "Tcp",
        });

        var scaleSet = new ScaleSet("vmscaleset",
                                    new ScaleSetArgs
        {
            ResourceGroupName = resourceGroup.Name,
            NetworkProfiles   = new ScaleSetNetworkProfileArgs
            {
                IpConfigurations = new ScaleSetNetworkProfileIpConfigurationArgs[] {
                    new ScaleSetNetworkProfileIpConfigurationArgs {
                        LoadBalancerBackendAddressPoolIds = bpePool.Id,
                        Name     = "IPConfiguration",
                        Primary  = true,
                        SubnetId = subnet.Id,
                    }
                },
                Name    = "networkprofile",
                Primary = true
            },
            OsProfile = new ScaleSetOsProfileArgs
            {
                ComputerNamePrefix = "vmlab",
                AdminUsername      = "******",
                AdminPassword      = "******",
                CustomData         =
                    @"#!/bin/bash
echo ""Hello, World by $HOSTNAME!"" > index.html
nohup python -m SimpleHTTPServer 80 &"
            },
            OsProfileLinuxConfig = new ScaleSetOsProfileLinuxConfigArgs
            {
                DisablePasswordAuthentication = false
            },
            Sku = new ScaleSetSkuArgs
            {
                Capacity = 1,
                Name     = "Standard_DS1_v2",
                Tier     = "Standard",
            },
            StorageProfileOsDisk = new ScaleSetStorageProfileOsDiskArgs
            {
                Caching         = "ReadWrite",
                CreateOption    = "FromImage",
                ManagedDiskType = "Standard_LRS",
                Name            = ""
            },
            StorageProfileDataDisks = new ScaleSetStorageProfileDataDiskArgs
            {
                Caching      = "ReadWrite",
                CreateOption = "Empty",
                DiskSizeGb   = 10,
                Lun          = 0
            },
            StorageProfileImageReference = new ScaleSetStorageProfileImageReferenceArgs
            {
                Offer     = "UbuntuServer",
                Publisher = "Canonical",
                Sku       = "16.04-LTS",
                Version   = "latest",
            },
            UpgradePolicyMode = "Manual"
        }, new CustomResourceOptions {
            DeleteBeforeReplace = true, DependsOn = bpePool
        });


        var autoscale = new AutoscaleSetting("vmss-autoscale",
                                             new AutoscaleSettingArgs
        {
            ResourceGroupName = resourceGroup.Name,
            Notification      = new AutoscaleSettingNotificationArgs
            {
                Email = new AutoscaleSettingNotificationEmailArgs
                {
                    CustomEmails = new string[] { "*****@*****.**" },
                    SendToSubscriptionAdministrator   = true,
                    SendToSubscriptionCoAdministrator = true,
                },
            },
            Profiles = new AutoscaleSettingProfileArgs[] {
                new AutoscaleSettingProfileArgs {
                    Capacity = new AutoscaleSettingProfileCapacityArgs
                    {
                        Default = 2,
                        Maximum = 10,
                        Minimum = 2,
                    },
                    Name  = "defaultProfile",
                    Rules = new AutoscaleSettingProfileRuleArgs[] {
                        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
        });



        // The public IP address is not allocated until the VM is running, so wait for that
        // resource to create, and then lookup the IP address again to report its public IP.
        this.IpAddress = Output
                         .Tuple <string, string, string>(scaleSet.Id, publicIp.Name, resourceGroup.Name)
                         .Apply <string>(async t =>
        {
            (_, string name, string resourceGroupName) = t;
            var ip = await GetPublicIP.InvokeAsync(new GetPublicIPArgs
            {
                Name = name, ResourceGroupName = resourceGroupName
            });
            return(ip.IpAddress);
        });
    }
Beispiel #7
0
        public string AutoScaleCloudService(string serviceName, string roleName)
        {
            AutoscaleClient autoscaleClient = new AutoscaleClient(cloudCredentials);

            AutoscaleSettingCreateOrUpdateParameters autoscaleCreateParams = new AutoscaleSettingCreateOrUpdateParameters()
            {
                Setting = new AutoscaleSetting()
                {
                    Enabled  = true,
                    Profiles = new List <AutoscaleProfile>
                    {
                        new AutoscaleProfile
                        {
                            Capacity = new ScaleCapacity
                            {
                                Default = "1",
                                Maximum = "10",
                                Minimum = "1"
                            },
                            Name       = "sampleProfile",
                            Recurrence = new Recurrence
                            {
                                Frequency = RecurrenceFrequency.Week,
                                Schedule  = new RecurrentSchedule
                                {
                                    Days = new List <String> {
                                        "Monday", "Thursday", "Friday"
                                    },
                                    Hours   = { 7, 19 },
                                    Minutes = new List <int> {
                                        0
                                    },
                                    TimeZone = "Eastern Standard Time"
                                }
                            },
                            Rules = new List <ScaleRule>
                            {
                                new ScaleRule
                                {
                                    MetricTrigger = new MetricTrigger
                                    {
                                        MetricName      = "PercentageCPU",
                                        MetricNamespace = "",
                                        MetricSource    = AutoscaleMetricSourceBuilder.BuildCloudServiceMetricSource(serviceName, roleName, true),
                                        Operator        = ComparisonOperationType.GreaterThanOrEqual,
                                        Threshold       = 80,
                                        Statistic       = MetricStatisticType.Average,
                                        TimeGrain       = TimeSpan.FromMinutes(5),
                                        TimeAggregation = TimeAggregationType.Average,
                                        TimeWindow      = TimeSpan.FromMinutes(30)
                                    },
                                    ScaleAction = new ScaleAction
                                    {
                                        Direction = ScaleDirection.Increase,
                                        Cooldown  = TimeSpan.FromMinutes(20),
                                        Type      = ScaleType.ChangeCount,
                                        Value     = "1"
                                    },
                                },
                                new ScaleRule
                                {
                                    MetricTrigger = new MetricTrigger
                                    {
                                        MetricName      = "PercentageCPU",
                                        MetricNamespace = "",
                                        MetricSource    = AutoscaleMetricSourceBuilder.BuildCloudServiceMetricSource(serviceName, roleName, true),
                                        Operator        = ComparisonOperationType.LessThanOrEqual,
                                        Threshold       = 60,
                                        Statistic       = MetricStatisticType.Average,
                                        TimeGrain       = TimeSpan.FromMinutes(5),
                                        TimeAggregation = TimeAggregationType.Average,
                                        TimeWindow      = TimeSpan.FromMinutes(30)
                                    },
                                    ScaleAction = new ScaleAction
                                    {
                                        Direction = ScaleDirection.Decrease,
                                        Cooldown  = TimeSpan.FromMinutes(20),
                                        Type      = ScaleType.ChangeCount,
                                        Value     = "1"
                                    },
                                }
                            }
                        }
                    }
                }
            };


            OperationResponse autoscaleResponse = autoscaleClient.Settings.CreateOrUpdate(
                AutoscaleResourceIdBuilder.BuildCloudServiceResourceId(serviceName, roleName, true),
                autoscaleCreateParams);

            string statusCode = autoscaleResponse.StatusCode.ToString();

            AutoscaleSettingGetResponse settingReponse   = autoscaleClient.Settings.Get(AutoscaleResourceIdBuilder.BuildCloudServiceResourceId(serviceName, roleName, true));
            AutoscaleSetting            autoscaleSetting = settingReponse.Setting;

            return(statusCode);
        }
Beispiel #8
0
        private static AutoscaleSetting CreateAutoscaleSetting(string resourceUri, string metricName, string metricNamespace)
        {
            var capacity = new ScaleCapacity
            {
                Default = "1",
                Maximum = "100",
                Minimum = "1"
            };

            var fixedDate = new TimeWindow()
            {
                End      = DateTime.Parse("2014-04-16T21:06:11.7882792Z"),
                Start    = DateTime.Parse("2014-04-15T21:06:11.7882792Z"),
                TimeZone = TimeZoneInfo.Utc.Id.ToString()
            };

            var recurrence = new Recurrence()
            {
                Frequency = RecurrenceFrequency.Week,
                Schedule  = new RecurrentSchedule()
                {
                    Days = new List <string> {
                        "Monday"
                    },
                    Hours = new List <int> {
                        0
                    },
                    Minutes  = new int[] { 10 },
                    TimeZone = "UTC-11"
                }
            };

            var rules = new ScaleRule[]
            {
                new ScaleRule()
                {
                    MetricTrigger = new MetricTrigger
                    {
                        MetricName        = metricName,
                        MetricNamespace   = metricNamespace,
                        MetricResourceUri = resourceUri,
                        Operator          = ComparisonOperationType.GreaterThan,
                        Statistic         = MetricStatisticType.Average,
                        Threshold         = 80.0,
                        TimeAggregation   = TimeAggregationType.Maximum,
                        TimeGrain         = TimeSpan.FromMinutes(1),
                        TimeWindow        = TimeSpan.FromHours(1)
                    },
                    ScaleAction = new ScaleAction
                    {
                        Cooldown  = TimeSpan.FromMinutes(20),
                        Direction = ScaleDirection.Increase,
                        Type      = ScaleType.ExactCount,
                        Value     = "10"
                    }
                }
            };

            AutoscaleSetting setting = new AutoscaleSetting
            {
                Name = "setting1",
                TargetResourceUri = resourceUri,
                Enabled           = true,
                Profiles          = new AutoscaleProfile[]
                {
                    new AutoscaleProfile()
                    {
                        Name       = "Profile1",
                        Capacity   = capacity,
                        FixedDate  = fixedDate,
                        Recurrence = null,
                        Rules      = rules
                    },
                    new AutoscaleProfile()
                    {
                        Name       = "Profile2",
                        Capacity   = capacity,
                        FixedDate  = null,
                        Recurrence = recurrence,
                        Rules      = rules
                    }
                }
            };

            return(setting);
        }