public GetAutoscaleSettingCommandTests() { insightsAutoscaleOperationsMock = new Mock <IAutoscaleOperations>(); insightsManagementClientMock = new Mock <InsightsManagementClient>(); commandRuntimeMock = new Mock <ICommandRuntime>(); cmdlet = new GetAutoscaleSettingCommand() { CommandRuntime = commandRuntimeMock.Object, InsightsManagementClient = insightsManagementClientMock.Object }; response = new AutoscaleSettingGetResponse() { RequestId = Guid.NewGuid().ToString(), StatusCode = HttpStatusCode.OK, Id = "", Location = "", Name = "", Properties = null, Tags = null, }; responseList = new AutoscaleSettingListResponse() { RequestId = Guid.NewGuid().ToString(), StatusCode = HttpStatusCode.OK, AutoscaleSettingResourceCollection = new AutoscaleSettingResourceCollection() { Value = new List <AutoscaleSettingResource>() { new AutoscaleSettingResource() { Id = "", Location = "", Name = "", Properties = null, Tags = null, }, } } }; insightsAutoscaleOperationsMock.Setup(f => f.GetSettingAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <CancellationToken>())) .Returns(Task.FromResult <AutoscaleSettingGetResponse>(response)) .Callback((string resourceGrp, string settingNm, CancellationToken t) => { resourceGroup = resourceGrp; settingName = settingNm; }); insightsAutoscaleOperationsMock.Setup(f => f.ListSettingsAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <CancellationToken>())) .Returns(Task.FromResult <AutoscaleSettingListResponse>(responseList)) .Callback((string resourceGrp, string targetResourceId, CancellationToken t) => { resourceGroup = resourceGrp; targetResourceUri = targetResourceId; }); insightsManagementClientMock.SetupGet(f => f.AutoscaleOperations).Returns(this.insightsAutoscaleOperationsMock.Object); }
public void Autoscale_GetSetting() { var expectedAutoscaleSetting = CreateAutoscaleSetting(ResourceUri, "CpuPercentage", string.Empty); var expectedAutoscaleSettingGetResponse = new AutoscaleSettingGetResponse() { Id = ResourceUri, Location = "East US", Tags = new Dictionary <string, string> { { "tag1", "value1" } }, Name = expectedAutoscaleSetting.Name, Properties = expectedAutoscaleSetting, RequestId = "request id", StatusCode = HttpStatusCode.OK }; var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(expectedAutoscaleSettingGetResponse.ToJson()), }; var handler = new RecordedDelegatingHandler(response); InsightsManagementClient customClient = this.GetInsightsManagementClient(handler); AutoscaleSettingGetResponse actualResponse = customClient.AutoscaleOperations.GetSetting("resourceGroup1", "setting1"); AreEqual(expectedAutoscaleSettingGetResponse.Properties, actualResponse.Properties); }
/// <summary> /// Converts an AutoscaleSettingGetResponse object into an AutoscaleSettingResource /// </summary> /// <param name="autoscaleSettingSpec">The AutoscaleSettingGetResponse</param> /// <returns>An AutoscaleSettingResource created from an AutoscaleSettingGetResponse object</returns> public static AutoscaleSettingResource ToAutoscaleSettingGetResponse(this AutoscaleSettingGetResponse autoscaleSettingSpec) { return(new AutoscaleSettingResource { Id = autoscaleSettingSpec.Id, Location = autoscaleSettingSpec.Location, Name = autoscaleSettingSpec.Name, Properties = autoscaleSettingSpec.Properties, Tags = autoscaleSettingSpec.Tags }); }
/// <summary> /// Initializes a new instance of the PSAutoscaleSetting class. /// </summary> /// <param name="autoscaleSettingSpec">The autoscale setting spec</param> public PSAutoscaleSetting(AutoscaleSettingGetResponse autoscaleSettingSpec) { // Keep the original values (types) in the base class base.Properties = autoscaleSettingSpec.Properties; base.Tags = autoscaleSettingSpec.Tags; this.Id = autoscaleSettingSpec.Id; this.Location = autoscaleSettingSpec.Location; this.Name = autoscaleSettingSpec.Name; this.Properties = new PSAutoscaleSettingProperty(autoscaleSettingSpec.Properties); this.Tags = new PSDictionaryElement(autoscaleSettingSpec.Tags); }
/// <summary> /// Execute the cmdlet /// </summary> protected override void ExecuteCmdletInternal() { if (string.IsNullOrWhiteSpace(this.Name)) { // Retrieve all the Autoscale settings for a resource group AutoscaleSettingListResponse result = this.InsightsManagementClient.AutoscaleOperations.ListSettingsAsync(resourceGroupName: this.ResourceGroup, targetResourceUri: null).Result; var records = result.AutoscaleSettingResourceCollection.Value.Select(e => this.DetailedOutput.IsPresent ? new PSAutoscaleSetting(e) : e); WriteObject(sendToPipeline: records, enumerateCollection: true); } else { // Retrieve a single Autoscale setting determined by the resource group and the rule name AutoscaleSettingGetResponse result = this.InsightsManagementClient.AutoscaleOperations.GetSettingAsync(resourceGroupName: this.ResourceGroup, autoscaleSettingName: this.Name).Result; WriteObject(sendToPipeline: this.DetailedOutput.IsPresent ? new PSAutoscaleSetting(result) : result.ToAutoscaleSettingGetResponse()); } }
/// <summary> /// Execute the cmdlet /// </summary> protected override void ProcessRecordInternal() { WriteWarning("This cmdlet is being modified to enable better experience and may contain breaking changes in a future release."); if (string.IsNullOrWhiteSpace(this.Name)) { // Retrieve all the Autoscale settings for a resource group AutoscaleSettingListResponse result = this.InsightsManagementClient.AutoscaleOperations.ListSettingsAsync(resourceGroupName: this.ResourceGroup, targetResourceUri: null).Result; var records = result.AutoscaleSettingResourceCollection.Value.Select(e => this.DetailedOutput.IsPresent ? new PSAutoscaleSetting(e) : e); WriteObject(sendToPipeline: records, enumerateCollection: true); } else { // Retrieve a single Autoscale setting determined by the resource group and the rule name AutoscaleSettingGetResponse result = this.InsightsManagementClient.AutoscaleOperations.GetSettingAsync(resourceGroupName: this.ResourceGroup, autoscaleSettingName: this.Name).Result; WriteObject(sendToPipeline: this.DetailedOutput.IsPresent ? new PSAutoscaleSetting(result) : result.ToAutoscaleSettingGetResponse()); } }
/// <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(); } } }
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); }