protected override void ProcessRecordInternal()
        {
            ServiceDiagnosticSettingsGetResponse result = this.InsightsManagementClient.ServiceDiagnosticSettingsOperations.GetAsync(this.ResourceId, CancellationToken.None).Result;

            PSServiceDiagnosticSettings psResult = new PSServiceDiagnosticSettings(result.Properties);

            WriteObject(psResult);
        }
        public GetDiagnosticSettingCommandTests(Xunit.Abstractions.ITestOutputHelper output)
        {
            ServiceManagemenet.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagemenet.Common.Models.XunitTracingInterceptor(output));
            insightsDiagnosticsOperationsMock = new Mock <IServiceDiagnosticSettingsOperations>();
            insightsManagementClientMock      = new Mock <InsightsManagementClient>();
            commandRuntimeMock = new Mock <ICommandRuntime>();
            cmdlet             = new GetAzureRmDiagnosticSettingCommand()
            {
                CommandRuntime           = commandRuntimeMock.Object,
                InsightsManagementClient = insightsManagementClientMock.Object
            };

            response = new ServiceDiagnosticSettingsGetResponse
            {
                RequestId  = Guid.NewGuid().ToString(),
                StatusCode = HttpStatusCode.OK,
                Properties = new ServiceDiagnosticSettings
                {
                    StorageAccountId = "/subscriptions/123/resourcegroups/rg/providers/microsoft.storage/accounts/myaccount",
                    Logs             = new List <LogSettings>
                    {
                        new LogSettings
                        {
                            Category = "TestCategory1",
                            Enabled  = true
                        },
                        new LogSettings
                        {
                            Category = "TestCategory2",
                            Enabled  = false
                        }
                    },
                    Metrics = new List <MetricSettings>
                    {
                        new MetricSettings
                        {
                            TimeGrain = TimeSpan.FromMinutes(1),
                            Enabled   = false
                        },
                        new MetricSettings
                        {
                            TimeGrain = TimeSpan.FromHours(1)
                        }
                    }
                }
            };

            insightsDiagnosticsOperationsMock.Setup(f => f.GetAsync(It.IsAny <string>(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <ServiceDiagnosticSettingsGetResponse>(response))
            .Callback((string resourceId, CancellationToken cancellationToken) =>
            {
                this.calledResourceId = resourceId;
            });

            insightsManagementClientMock.SetupGet(f => f.ServiceDiagnosticSettingsOperations).Returns(this.insightsDiagnosticsOperationsMock.Object);
        }
        public void LogProfiles_GetTest()
        {
            var diagnosticSettings = CreateDiagnosticSettings();
            var expectedResponse   = new ServiceDiagnosticSettingsGetResponse()
            {
                Name       = "service",
                Properties = diagnosticSettings,
                RequestId  = "request id",
                StatusCode = HttpStatusCode.OK
            };

            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(expectedResponse.ToJson()),
            };

            var handler = new RecordedDelegatingHandler(response);
            InsightsManagementClient             customClient   = this.GetInsightsManagementClient(handler);
            ServiceDiagnosticSettingsGetResponse actualResponse = customClient.ServiceDiagnosticSettingsOperations.Get(ResourceUri);

            AreEqual(expectedResponse.Properties, actualResponse.Properties);
        }
        protected override void ProcessRecordInternal()
        {
            var putParameters = new ServiceDiagnosticSettingsPutParameters();

            ServiceDiagnosticSettingsGetResponse getResponse = this.InsightsManagementClient.ServiceDiagnosticSettingsOperations.GetAsync(this.ResourceId, CancellationToken.None).Result;

            ServiceDiagnosticSettings properties = getResponse.Properties;

            if (this.Enabled && string.IsNullOrWhiteSpace(this.StorageAccountId))
            {
                throw new ArgumentException("StorageAccountId can't be null when enabling");
            }

            if (!string.IsNullOrWhiteSpace(this.StorageAccountId))
            {
                properties.StorageAccountId = this.StorageAccountId;
            }

            if (this.Categories == null && this.Timegrains == null)
            {
                foreach (var log in properties.Logs)
                {
                    log.Enabled = this.Enabled;
                }

                foreach (var metric in properties.Metrics)
                {
                    metric.Enabled = this.Enabled;
                }
            }
            else
            {
                if (this.Categories != null)
                {
                    foreach (string category in this.Categories)
                    {
                        LogSettings logSettings = properties.Logs.FirstOrDefault(x => string.Equals(x.Category, category, StringComparison.OrdinalIgnoreCase));

                        if (logSettings == null)
                        {
                            throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Log category '{0}' is not available for '{1}'", category, this.StorageAccountId));
                        }

                        logSettings.Enabled = this.Enabled;
                    }
                }

                if (this.Timegrains != null)
                {
                    foreach (string timegrainString in this.Timegrains)
                    {
                        TimeSpan       timegrain      = XmlConvert.ToTimeSpan(timegrainString);
                        MetricSettings metricSettings = properties.Metrics.FirstOrDefault(x => TimeSpan.Equals(x.TimeGrain, timegrain));

                        if (metricSettings == null)
                        {
                            throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Metric timegrain '{0}' is not available for '{1}'", timegrainString, this.StorageAccountId));
                        }
                        metricSettings.Enabled = this.Enabled;
                    }
                }
            }

            putParameters.Properties = properties;

            this.InsightsManagementClient.ServiceDiagnosticSettingsOperations.PutAsync(this.ResourceId, putParameters, CancellationToken.None).Wait();
            PSServiceDiagnosticSettings psResult = new PSServiceDiagnosticSettings(putParameters.Properties);

            WriteObject(psResult);
        }
        /// <summary>
        /// Gets the status of the diagnostic settings being applied. Once it
        /// is successfull, it will replace the current diagnostic settings.
        /// To get the active one, use Get.
        /// </summary>
        /// <param name='resourceUri'>
        /// Required. The resource identifier of the configuration.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        public async Task <ServiceDiagnosticSettingsGetResponse> GetStatusAsync(string resourceUri, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceUri == null)
            {
                throw new ArgumentNullException("resourceUri");
            }

            // Tracing
            bool   shouldTrace  = TracingAdapter.IsEnabled;
            string invocationId = null;

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

            // Construct URL
            string url = "/" + Uri.EscapeDataString(resourceUri) + "/diagnosticSettings/service/poll?";

            url = url + "api-version=2014-04-01";
            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");

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

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

                    if (shouldTrace)
                    {
                        TracingAdapter.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)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    ServiceDiagnosticSettingsGetResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

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

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

                            JToken locationValue = responseDoc["location"];
                            if (locationValue != null && locationValue.Type != JTokenType.Null)
                            {
                                string locationInstance = ((string)locationValue);
                                result.Location = locationInstance;
                            }

                            JToken propertiesValue = responseDoc["properties"];
                            if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
                            {
                                ServiceDiagnosticSettings propertiesInstance = new ServiceDiagnosticSettings();
                                result.Properties = propertiesInstance;

                                JToken storageAccountNameValue = propertiesValue["storageAccountName"];
                                if (storageAccountNameValue != null && storageAccountNameValue.Type != JTokenType.Null)
                                {
                                    string storageAccountNameInstance = ((string)storageAccountNameValue);
                                    propertiesInstance.StorageAccountName = storageAccountNameInstance;
                                }

                                JToken statusValue = propertiesValue["status"];
                                if (statusValue != null && statusValue.Type != JTokenType.Null)
                                {
                                    DiagnosticSettingsStatus statusInstance = ((DiagnosticSettingsStatus)Enum.Parse(typeof(DiagnosticSettingsStatus), ((string)statusValue), true));
                                    propertiesInstance.Status = statusInstance;
                                }
                            }
                        }
                    }
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
Exemplo n.º 6
0
        public SetDiagnosticSettingCommandTests()
        {
            insightsDiagnosticsOperationsMock = new Mock <IServiceDiagnosticSettingsOperations>();
            insightsManagementClientMock      = new Mock <InsightsManagementClient>();
            commandRuntimeMock = new Mock <ICommandRuntime>();
            cmdlet             = new SetAzureRmDiagnosticSettingCommand()
            {
                CommandRuntime           = commandRuntimeMock.Object,
                InsightsManagementClient = insightsManagementClientMock.Object
            };

            response = new ServiceDiagnosticSettingsGetResponse
            {
                RequestId  = Guid.NewGuid().ToString(),
                StatusCode = HttpStatusCode.OK,
                Properties = new ServiceDiagnosticSettings
                {
                    StorageAccountId = storageAccountId,
                    Logs             = new List <LogSettings>
                    {
                        new LogSettings
                        {
                            Category = "TestCategory1",
                            Enabled  = true
                        },
                        new LogSettings
                        {
                            Category = "TestCategory2",
                            Enabled  = false
                        }
                    },
                    Metrics = new List <MetricSettings>
                    {
                        new MetricSettings
                        {
                            TimeGrain = TimeSpan.FromMinutes(1),
                            Enabled   = false
                        },
                        new MetricSettings
                        {
                            TimeGrain = TimeSpan.FromHours(1),
                            Enabled   = true
                        }
                    }
                }
            };

            insightsDiagnosticsOperationsMock.Setup(f => f.GetAsync(It.IsAny <string>()))
            .Returns(Task.FromResult <ServiceDiagnosticSettingsGetResponse>(response))
            .Callback((string resourceId) =>
            {
                this.calledResourceId = resourceId;
            });

            insightsDiagnosticsOperationsMock.Setup(f => f.PutAsync(It.IsAny <string>(), It.IsAny <ServiceDiagnosticSettingsPutParameters>()))
            .Returns(Task.FromResult <EmptyResponse>(new EmptyResponse()))
            .Callback((string resourceId, ServiceDiagnosticSettingsPutParameters putParameters) =>
            {
                this.calledResourceId    = resourceId;
                this.calledPutParameters = putParameters;
            });

            insightsManagementClientMock.SetupGet(f => f.ServiceDiagnosticSettingsOperations).Returns(this.insightsDiagnosticsOperationsMock.Object);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Gets the active diagnostic settings. To get the diagnostic settings
        /// being applied, use GetStatus.
        /// </summary>
        /// <param name='resourceUri'>
        /// Required. The resource identifier of the configuration.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        public async Task <ServiceDiagnosticSettingsGetResponse> GetAsync(string resourceUri, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceUri == null)
            {
                throw new ArgumentNullException("resourceUri");
            }

            // Tracing
            bool   shouldTrace  = TracingAdapter.IsEnabled;
            string invocationId = null;

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

            // Construct URL
            string url = "";

            url = url + "/";
            url = url + Uri.EscapeDataString(resourceUri);
            url = url + "/providers/microsoft.insights/diagnosticSettings/service";
            List <string> queryParameters = new List <string>();

            queryParameters.Add("api-version=2015-07-01");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            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");

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

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

                    if (shouldTrace)
                    {
                        TracingAdapter.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)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    ServiceDiagnosticSettingsGetResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

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

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

                            JToken locationValue = responseDoc["location"];
                            if (locationValue != null && locationValue.Type != JTokenType.Null)
                            {
                                string locationInstance = ((string)locationValue);
                                result.Location = locationInstance;
                            }

                            JToken propertiesValue = responseDoc["properties"];
                            if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
                            {
                                ServiceDiagnosticSettings propertiesInstance = new ServiceDiagnosticSettings();
                                result.Properties = propertiesInstance;

                                JToken storageAccountIdValue = propertiesValue["storageAccountId"];
                                if (storageAccountIdValue != null && storageAccountIdValue.Type != JTokenType.Null)
                                {
                                    string storageAccountIdInstance = ((string)storageAccountIdValue);
                                    propertiesInstance.StorageAccountId = storageAccountIdInstance;
                                }

                                JToken serviceBusRuleIdValue = propertiesValue["serviceBusRuleId"];
                                if (serviceBusRuleIdValue != null && serviceBusRuleIdValue.Type != JTokenType.Null)
                                {
                                    string serviceBusRuleIdInstance = ((string)serviceBusRuleIdValue);
                                    propertiesInstance.ServiceBusRuleId = serviceBusRuleIdInstance;
                                }

                                JToken storageAccountNameValue = propertiesValue["storageAccountName"];
                                if (storageAccountNameValue != null && storageAccountNameValue.Type != JTokenType.Null)
                                {
                                    string storageAccountNameInstance = ((string)storageAccountNameValue);
                                    propertiesInstance.StorageAccountName = storageAccountNameInstance;
                                }

                                JToken metricsArray = propertiesValue["metrics"];
                                if (metricsArray != null && metricsArray.Type != JTokenType.Null)
                                {
                                    foreach (JToken metricsValue in ((JArray)metricsArray))
                                    {
                                        MetricSettings metricSettingsInstance = new MetricSettings();
                                        propertiesInstance.Metrics.Add(metricSettingsInstance);

                                        JToken timeGrainValue = metricsValue["timeGrain"];
                                        if (timeGrainValue != null && timeGrainValue.Type != JTokenType.Null)
                                        {
                                            TimeSpan timeGrainInstance = XmlConvert.ToTimeSpan(((string)timeGrainValue));
                                            metricSettingsInstance.TimeGrain = timeGrainInstance;
                                        }

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

                                        JToken retentionPolicyValue = metricsValue["retentionPolicy"];
                                        if (retentionPolicyValue != null && retentionPolicyValue.Type != JTokenType.Null)
                                        {
                                            RetentionPolicy retentionPolicyInstance = new RetentionPolicy();
                                            metricSettingsInstance.RetentionPolicy = retentionPolicyInstance;

                                            JToken enabledValue2 = retentionPolicyValue["enabled"];
                                            if (enabledValue2 != null && enabledValue2.Type != JTokenType.Null)
                                            {
                                                bool enabledInstance2 = ((bool)enabledValue2);
                                                retentionPolicyInstance.Enabled = enabledInstance2;
                                            }

                                            JToken daysValue = retentionPolicyValue["days"];
                                            if (daysValue != null && daysValue.Type != JTokenType.Null)
                                            {
                                                int daysInstance = ((int)daysValue);
                                                retentionPolicyInstance.Days = daysInstance;
                                            }
                                        }
                                    }
                                }

                                JToken logsArray = propertiesValue["logs"];
                                if (logsArray != null && logsArray.Type != JTokenType.Null)
                                {
                                    foreach (JToken logsValue in ((JArray)logsArray))
                                    {
                                        LogSettings logSettingsInstance = new LogSettings();
                                        propertiesInstance.Logs.Add(logSettingsInstance);

                                        JToken categoryValue = logsValue["category"];
                                        if (categoryValue != null && categoryValue.Type != JTokenType.Null)
                                        {
                                            string categoryInstance = ((string)categoryValue);
                                            logSettingsInstance.Category = categoryInstance;
                                        }

                                        JToken enabledValue3 = logsValue["enabled"];
                                        if (enabledValue3 != null && enabledValue3.Type != JTokenType.Null)
                                        {
                                            bool enabledInstance3 = ((bool)enabledValue3);
                                            logSettingsInstance.Enabled = enabledInstance3;
                                        }

                                        JToken retentionPolicyValue2 = logsValue["retentionPolicy"];
                                        if (retentionPolicyValue2 != null && retentionPolicyValue2.Type != JTokenType.Null)
                                        {
                                            RetentionPolicy retentionPolicyInstance2 = new RetentionPolicy();
                                            logSettingsInstance.RetentionPolicy = retentionPolicyInstance2;

                                            JToken enabledValue4 = retentionPolicyValue2["enabled"];
                                            if (enabledValue4 != null && enabledValue4.Type != JTokenType.Null)
                                            {
                                                bool enabledInstance4 = ((bool)enabledValue4);
                                                retentionPolicyInstance2.Enabled = enabledInstance4;
                                            }

                                            JToken daysValue2 = retentionPolicyValue2["days"];
                                            if (daysValue2 != null && daysValue2.Type != JTokenType.Null)
                                            {
                                                int daysInstance2 = ((int)daysValue2);
                                                retentionPolicyInstance2.Days = daysInstance2;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }